Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing cookies in a WPF WebBrowser control?

Is there a way to read/write the cookies that a WebBrowser control uses?

I am doing something like this...

string resultHtml;
HttpWebRequest request = CreateMyHttpWebRequest(); // fills http headers and stuff
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    resultHtml = sr.ReadToEnd();
}
WebBrowser browser = new WebBrowser();
browser.CookieContainer = request.CookieContainer; // i wish i could do this :(
browser.NavigateToString(resultHtml);  
like image 395
kenwarner Avatar asked Dec 29 '09 16:12

kenwarner


2 Answers

One of the potentially confusing things about the WebBrowser control and cookies is that at a first glance, it often looks like your app gets a separate cookie store. For example, if you log into a site that stores a persistent cookie to identify you, then whether you appear to be logged in for that site from inside an app hosting the control will be independent of whether you seem to be logged in via Internet Explorer.

In fact, you can even be logged in with different identities.

However, although it might be natural to draw the conclusion that each app hosting the WebBrowser therefore gets its own cookies, in fact that's not true. There are merely two sets of cookies: the ones used in 'low integrity' mode (which is what IE runs in by default), and the other set, which is what you'll get in a normal app that hosts the WebBrowser and also what you'll get if you run IE elevated.

like image 112
Ian Griffiths Avatar answered Sep 30 '22 00:09

Ian Griffiths


the webbrowser control uses WinInet for networking, specifically use the InternetSetCookie(Ex) and InternetGetCookie(Ex) functions for Cookie management. There isn't a WinInet wrapper in .Net, but you can p-invoke.

like image 21
Sheng Jiang 蒋晟 Avatar answered Sep 29 '22 23:09

Sheng Jiang 蒋晟