Monday, August 27, 2007

WebClient: Handling Cookies

WebClient class is very useful when you need to download or upload date from or to the Web.  However, when you need to make a sequence of calls you find that WebClient does not preserve cookies set by the server between requests.  Fortunately, WebClient gives you an opportunity to handle cookies by yourself. 

The very simple solution is to override GetWebRequest method of the WebClient class and set CookieContainer property.

Here is my implementation:

    public class CookieAwareWebClient : WebClient
{

private CookieContainer m_container = new CookieContainer();

protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}

7 comments:

ciberch said...

Cool this works awesome !

pani Massacre said...

ugh you have help me so many times with this. thank you so much.

Anonymous said...

brilliantly simple - thank you

Anonymous said...

Thank you. Very useful info!

Anonymous said...

Brilliant solution! Saved me a couple of hours. Thanks!

Raphael Ng said...

Thanks, thanks and a lot of thanks!!

Leon de Almeida said...

Oh, yes - thanks from Brazil!