Richard Lemmens website

Cookie aware WebClient

Microsoft's WebClient class is a useful thingy. Too bad that is unaware of cookies. This can be easily amended by subclassing and expanding it:

			
namespace myNamespace
{
    /// <summary>
    /// Subclass of WebClient that can handle cookies.
    /// </summary>
    public class CookieAwareWebClient : System.Net.WebClient
    {
        /// <summary>
        /// Gets or sets the cookies.
        /// </summary>
        public System.Net.CookieContainer CookieContainer { get; set; }

        /// <summary>
        /// Gets or sets the URI.
        /// </summary>
        public System.Uri Uri { get; set; }

        /// <summary>
        /// Creates a new instance of the CookieAwareWebClient class without cookies.
        /// </summary>
        public CookieAwareWebClient()
            : this(new System.Net.CookieContainer())
        { }

        /// <summary>
        /// Creates a new instance of the CookieAwareWebClient class with cookies.
        /// </summary>
        public CookieAwareWebClient(System.Net.CookieContainer cookies)
        {
            this.CookieContainer = cookies;
        }

        /// <summary>
        /// Creates a WebRequest object for a resource.
        /// </summary>
        /// <param name="address">URI of the resource</param>
        /// <returns>WebRequest object</returns>
        protected override System.Net.WebRequest GetWebRequest(System.Uri address)
        {
            System.Net.WebRequest request = base.GetWebRequest(address);
            if (request is System.Net.HttpWebRequest)
            {
                (request as System.Net.HttpWebRequest).CookieContainer = this.CookieContainer;
            }
            System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest) request;
            httpRequest.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
            return httpRequest;
        }

        // To process response cookies, override the GetWebResponse method too
    }
}