6
votes

is there a way to make the WebBrowser control in C#.NET and requests made by HttpWebRequest share cookies?

E.g. if a request is made programmatically with HttpWebRequest and then the HttpWebResponse sets a cookie, is there a way to make sure this is also set in the WebBrowser control?

and likewise, if the user navigates with the WebBrowser control and a cookie is set, is there a way to ensure the CookieContainer for the HttpWebRequest is also updated?

Thanks for any help!

2

2 Answers

3
votes

You'd need to synchronize the cookies manually using the InternetSetCookieEx / InternetGetCookieEx APIs, and this would require that you know all of the URLs of all of the subdownloads used by the page in question.

You also need to pass the INTERNET_COOKIE_HTTPONLY flag to ensure that HTTPONLY cookies are seen by your application.

1
votes
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUri);
request.CookieContainer = new CookieContainer();
request.CookieContainer.SetCookies(myUri, webBrowser1.Document.Cookie);

(source)

And vice versa (I'm not sure):

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUri);
//request.CookieContainer = new CookieContainer();
request.GetResponse();
webBrowser1.Document.Cookie = request.CookieContainer.GetCookies(myUri);