Question

I'm trying to display a web page which requires one to be logged in first. I'm using HttpWebRequest/Response objects to accomplish the logging in part, by collecting the session and authorization cookies in the background.

After logging in, a HttpWebResponse object returns to me the HTML page that I want to show the user via the WebBrowser control, so I know I have the right set of session/authorization cookies to get to the desired web page.

Having the CookieContainer properly populated with relevant cookies, I set the WebBrowser.DocumentText property to a prepared HTML which contains a GET command to the web address I'm trying to display. The browser pops-up trying to render the prepared HTML and I get a server error relating to missing cookies, I assume.

When I try to set WebBrowser.Document.Cookie prior to calling the DocumentText property, in the debugger I'm seeing, that the Cookie property always remains null after trying to set it to a string of the form "cookName=cookValue; cookName=cookValue;".

Why does the Cookie property reject the cookies string I'm passing it? Does this have something to do with HttpOnly cookies? Is my cookie string incorrectly formatted? Am I trying to set the Cookie property at the wrong time?

I did the WebBrowser.Navigate("about:blank") call, which seems to be required to properly initialize the WebBrowser object.

Was it helpful?

Solution

Here is what worked for me:

  using System.Runtime.InteropServices;

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

  //'CookieCollection' was populated using HttpWebRequest/Response calls
  int i=0;
  InternetSetCookie("https://www.myurl.com/", null, CookieCollection[i++].ToString() + "; expires = Sun, 01-Jan-2013 00:00:00 GMT");
  //repeat for however many cookies you've got

  browser.Navigate("https://www.myurl.com/tools/..../Index.aspx?t=someValue", true);
  //or
  browser.DocumentText = someHtml;

Notes:

1) Without including the "expires" value the InternetSetCookie call did not work despite returning 'true'. The "expires" value turns the cookie into a persistent cookie as opposed to a session only cookie.

2) 'browser.Navigate("about:blank");' does not seem to be required. I was able to get at my page with and without this statement.

3) browser.Document.Cookie never worked for me (always null), no matter what I threw at it. And I've tried a lot of different strings, including the one passed into the third parameter of InternetSetCookie.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top