locked
Does webclient handle cookie? RRS feed

  • Question

  • Does webclient keep a internal cookie container and save/post cookies so the users don't need to handle cookie?
    Tuesday, August 3, 2010 10:39 PM

Answers

  • You can modify the WebClient to support cookies:

    public class CookedWebClient : WebClient
    {
    
      CookieContainer cookies = new CookieContainer();
    
      public CookieContainer Cookies{ get{ return cookies; } }
    
      protected override WebRequest GetWebRequest(Uri address)
      {
    
        WebRequest request = base.GetWebRequest(address);
    
        if(request.GetType() == typeof(HttpWebRequest))
          ((HttpWebRequest)request).CookieContainer = cookies;
    
        return request;
    
      }
    
    }
    

    • Marked as answer by Figo Fei Wednesday, August 11, 2010 8:13 AM
    Tuesday, August 3, 2010 11:40 PM
  • WebClient does not have built-in support for cookies.

    The purpose of WebClient is to provide an easy-to-use wrapper for HttpWebRequest.  You can use HttpWebRequest instead if you need more functionality.  It is not all that much harder to use.  HttpWebRequest has support for cookies.

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx

    http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.cookies.aspx

    • Marked as answer by Figo Fei Wednesday, August 11, 2010 8:13 AM
    Tuesday, August 3, 2010 11:03 PM

All replies

  • WebClient does not have built-in support for cookies.

    The purpose of WebClient is to provide an easy-to-use wrapper for HttpWebRequest.  You can use HttpWebRequest instead if you need more functionality.  It is not all that much harder to use.  HttpWebRequest has support for cookies.

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx

    http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.cookies.aspx

    • Marked as answer by Figo Fei Wednesday, August 11, 2010 8:13 AM
    Tuesday, August 3, 2010 11:03 PM
  • You can modify the WebClient to support cookies:

    public class CookedWebClient : WebClient
    {
    
      CookieContainer cookies = new CookieContainer();
    
      public CookieContainer Cookies{ get{ return cookies; } }
    
      protected override WebRequest GetWebRequest(Uri address)
      {
    
        WebRequest request = base.GetWebRequest(address);
    
        if(request.GetType() == typeof(HttpWebRequest))
          ((HttpWebRequest)request).CookieContainer = cookies;
    
        return request;
    
      }
    
    }
    

    • Marked as answer by Figo Fei Wednesday, August 11, 2010 8:13 AM
    Tuesday, August 3, 2010 11:40 PM