ty.
ty.

Reputation: 11132

Setting a cookie in a WebBrowser control

I am loading a website using a WebBrowser's Navigate function, and I want the browser to load the page with a cookie I've given it.

The following code doesn't work:

wb.Navigate(url, null, null, "Cookie: " + cookie + "\n");

What am I doing wrong? Will I have to use InternetSetCookie? This doesn't seem like the best solution.

Upvotes: 23

Views: 45873

Answers (3)

Zacharious
Zacharious

Reputation: 555

The proper way is using InternetSetCookieEx.

[DllImport("wininet.dll")]
static extern InternetCookieState InternetSetCookieEx(
    string lpszURL,
    string lpszCookieName,
    string lpszCookieData,
    int dwFlags,
    int dwReserved);

enum InternetCookieState : int
{
    COOKIE_STATE_UNKNOWN = 0x0,
    COOKIE_STATE_ACCEPT = 0x1,
    COOKIE_STATE_PROMPT = 0x2,
    COOKIE_STATE_LEASH = 0x3,
    COOKIE_STATE_DOWNGRADE = 0x4,
    COOKIE_STATE_REJECT = 0x5,
    COOKIE_STATE_MAX = COOKIE_STATE_REJECT
} 

Here's some code to test it at a website that shows your HTTP headers.

InternetSetCookieEx("http://request.urih.com/", null, "TestData=Test;", 0, 0);
webBrowser1.Navigate("http://request.urih.com/");

Upvotes: 3

Łukasz Włodarczyk
Łukasz Włodarczyk

Reputation: 1

Something is wrong with cookies in thin control. There is overload for navigate method with cookie:

string cookie = webBrowser1.Document.Cookie.ToString(); webBrowser1.Navigate(url,"",null, cookie);

In my case problem was resolved by redirecting to the page twice (or three times repeated) so look like this control enables cookies automatically:

           `webBrowser1.Navigate(url);
            waitforwebsite(300, webBrowser1);
            webBrowser1.Navigate(url);
            waitforwebsite(300, webBrowser1);
            webBrowser1.Navigate(url);`

Upvotes: 0

Kiran Madipally
Kiran Madipally

Reputation: 847

Looks like there is a better way:

Import the InternetSetCookie function:

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

Create the Cookie object:

Cookie temp1 = new Cookie("KEY1", "VALUE1", "/Path/To/My/App", "/");

Call InternetSetCookie function to set the cookie for that URL

InternetSetCookie("https://my.url.com/Path/To/My/App", null, temp1.ToString() + "; expires = Sun, 01-Jan-2013 00:00:00 GMT");

Navigate the WebBrowser to the URL you would like to go to.

webBrowser1.Navigate("https://my.url.com/Path/To/My/App");

Think this is the best solution for the issue :).

Upvotes: 24

Related Questions