Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cookies from CookieContainer in WebBrowser

Is there any way that I can actually use the cookies from a cookie container (taken from a WebRequest previously) and use them in a WebBrowser control? If so, how would I do this? This is for a Winforms application in C#.

like image 948
Alex Avatar asked Nov 15 '10 14:11

Alex


2 Answers

You need to make use of InternetSetCookie. Here is a sample...

public partial class WebBrowserControl : Form
{
     private String url;

     [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
     public static extern bool InternetSetCookie(string lpszUrlName, string    lbszCookieName, string lpszCookieData);

     public WebBrowserControl(String path)
     {
          this.url = path;
          InitializeComponent();

          // set cookie
          InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID); 

          // navigate
          webBrowser.Navigate(url); 
     }
}
like image 84
Aaron McIver Avatar answered Sep 28 '22 04:09

Aaron McIver


Here's an example oh how this could be achieved:

private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }

    public CookieContainer CookieContainer { get; private set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        var httpRequest = request as HttpWebRequest;
        if (httpRequest != null)
        {
            httpRequest.CookieContainer = CookieContainer;
        }
        return request;
    }
}


private void Form1_Load(object sender, EventArgs e)
{
    using (var client = new CookieAwareWebClient())
    {
        client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        client.DownloadData("http://www.google.com");
        var cookies = client.CookieContainer.GetCookies(new Uri("http://www.google.com"));
        var prefCookie = cookies["PREF"];
        webBrowser1.Navigate("http://www.google.com", "", null, "Cookie: " + prefCookie.Value + Environment.NewLine);
    }
}
like image 24
Darin Dimitrov Avatar answered Sep 28 '22 04:09

Darin Dimitrov