Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse


Is there any way to automatically handle cookies in .NET with the HttpWebRequest/HttpWebResponse objects? I'm preferably looking for an equivalent to LWP::UserAgent and its behaviour (perl), only in a .NET environment.

Any suggestions or advice?

8/27/2011 4:35:34 PM

Accepted Answer

I think what you're looking for is the CookieContainer class. If I understand what you're trying to do correctly, you have separate objects for request & response, and you want to transfer the response cookie collection into the next request cookie collection automatically. Try using this code:

CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("");
request.CookieContainer = cookieJar;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;

Once you create a cookieJar and set it to the request's CookieContainer, it will store any cookies that come from the response, so in the example above, the cookie jar's count will be 1 once it visits The cookie container properties of the request & response above will store a pointer to the cookieJar, so the cookies are automatically handled and shared between the objects.

2/21/2009 3:44:05 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow