HttpWebResponse.Cookies

  • Thread starter Thread starter Prasanna Padmanabhan
  • Start date Start date
P

Prasanna Padmanabhan

I am writing a simple HTTP Client in .NET. I make an HTTP Request and
examine the response.

I get an empty CookieCollection when I do HttpWebResponse.Cookies. However
HttpWebResponse.Headers[Set-Cookie] returns the correct list of cookies
(represented as a comma-separated string) in the response.

Can someone please explain the discrepancy?

Thanks,
Prasanna
 
If you're making several requests and would like the cookies to be maintained
across all of those requests you should initialize the HttpWebRequest.CookieContainer
for each of those requests with an instance you have around. So like this:

CookieContainer cookies = new CookieContainer();
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("Page1.aspx");
r.CookieContainer = cookies;
// do r.GetResponse()
r = (HttpWebRequest)WebRequest.Create("Page2.aspx");
r.CookieContainer = cookies;

Also, even if you're just doing a single request, it's possible the page
does a redirect and the HttpWebRequest handles this automatically, but unless
you've given it a CookieContainer it will drop cookies across the redirect.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
Back
Top