在WebBrowser控件中设置cookie

我正在使用WebBrowser的Navigatefunction加载网站,我希望浏览器加载带有我给它的cookie的页面。

以下代码不起作用:

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

我究竟做错了什么? 我必须使用InternetSetCookie吗? 这似乎不是最好的解决方案。

看起来有更好的方法:

导入InternetSetCookie函数:

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

创建Cookie对象:

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

调用InternetSetCookie函数来设置该URL的cookie

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

WebBrowser Navigate到您要访问的URL。

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

认为这是问题的最佳解决方案:)。

正确的方法是使用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 } 

这里有一些代码可以在显示HTTP标头的网站上进行测试。

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