2010-05-13 92 views
22

我使用WebBrowser的导航功能加载网站,并且我希望浏览器使用我提供的cookie加载页面。在WebBrowser控件中设置Cookie

下面的代码不起作用:

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

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

+0

您是否找到了答案? – 2012-04-25 15:35:00

+0

不幸的是,没有。 – 2012-05-31 22:18:58

回答

19

貌似有一个更好的办法:

导入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功能设置cookie为URL

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

NavigateWebBrowser到你想要去的URL。

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

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

+1

对于任何想从DateTime对象中获取'expires ='部分的人,请按照以下步骤操作:myDateTimeObj.ToUniversalTime().ToString("ddd, dd-MMM-yyyy HH:mm:ss") + " GMT" Daniel 2013-06-06 14:51:31

+0

链接已死,但幸好您粘贴了代码! – TEK 2015-05-21 20:41:42

+0

如果您需要在会话的内存中设置cookie,您可以直接拨打: InternetSetCookieEx(“https://my.url.com/Path/To/My/App”,“KEY1”,“VALUE1” ,NULL,NULL)。 注意:调用InternetSetCookie和InternetSetCookieEx是有区别的(http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx)。在实践中,我发现只有使用“Ex”方法时,页面发出的任何后续请求才包含cookie。 – 2015-07-15 13:37:06

3

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 
} 

下面是一些代码在website that shows your HTTP headers进行测试。

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

当我这样做时,我收到了重复的Cookie。已尝试cookie域,并且没有结束斜线。尝试了有和没有分号的值。试过不修剪名称/值对并修剪。 我只是想知道在生产中是否发现问题,修复了Cookie的设置,或许没有更新您的答案。 – 2018-03-06 10:07:59

+0

为了澄清,当我设置cookie时,我保存在数据库中,然后第三方网站设置它们,它们最终会重复。 – 2018-03-06 20:39:19