Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone:
I am new in .net programming and need some help. My intention is to post data to a web server and get desired service. The functionality of the program in my mind is that:
After an initial log-in session with username/password, the following sessions only accepts key-value pairs for a required service -- this is the way the server supposed to provide the service.

I found an implementation code for a Cookie-awared WebClient class that may be a solution, attached as following. But it does not work. The problem is: the cookies from the first session was not well captured, so subsequent sessions lack the desired information to work properly.

Is there a more detailed example on how to realize the function?

Thank you in advance!

Jacob

C#
public class WebClient_CookieAware : WebClient
 {
     public CookieContainer theCookieContainer { get; set; }
     public Uri Uri { get; set; }
     public WebClient_Cookie(): this(new CookieContainer())
          {    }

     public WebClient_Cookie(CookieContainer cookies)
        {
         this.theCookieContainer = cookies;
         }

     protected override WebRequest GetWebRequest(Uri address)
     {
         WebRequest request = base.GetWebRequest(address);
         if (request is HttpWebRequest)
             { (request as HttpWebRequest).CookieContainer = theCookieContainer;}
         HttpWebRequest httpRequest = (HttpWebRequest)request;
         // httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
         return httpRequest;
     }

     protected override WebResponse GetWebResponse(WebRequest request)
     {
         WebResponse response = base.GetWebResponse(request);
         String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
         if (setCookieHeader == null)
         {
             Cookie cookie = new Cookie();
             this.theCookieContainer.Add(cookie);
         }
         return response;
     }
 }
Posted
Updated 14-Sep-11 17:14pm
v2
Comments
Prerak Patel 14-Sep-11 23:14pm    
Added code block.

1 solution

Take a look at this code:
C#
WebRequest webRequest;
WebResponse webResponse;
string string_Field = webResponse.Headers[HttpResponseHeader.SetCookie];
webRequest.Headers.Add(HttpRequestHeader.Cookie, string_Field);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900