无法设置cookie:Cef.SetCookie()始终返回false

问题描述 投票:1回答:3

这个问题让我困惑了好几天了。我完全无法使用CefSharp设置cookie。

这是我期望工作的代码块(更多是因为它可以是天真的,不包括显式线程上下文切换):

Application.Current.Dispatcher.Invoke(new Action(() =>
{
    var settings = new CefSettings();
    settings.CachePath = "cookies";

    Cef.Initialize(settings);

    Cef.DeleteCookies("", ""); 
    Cef.VisitAllCookies(new CookieVisitor());  // <-- doesn't get called, so assuming we've cleared all the persistent cookies here...

    Cef.SetCookiePath("/", false);
    Cef.VisitAllCookies(new CookieVisitor());  // <-- ok guess im paranoid...
    var isSet = Cef.SetCookie("/", "username", 
                    "testuser", "tovalrsv01", "/", 
                    false, false, false, new DateTime(2020, 1, 1));

    Cef.VisitAllCookies(new CookieVisitor()); // <-- isSet is false, and i don't see the cookie that i created in the visited list...
}));

我只是想知道我是否错过了一些重要的概念。我是CefSharp的新手,尽管已经仔细研究了这些例子和论坛,但我很可能在这里错过了一些东西。非常感谢任何见解或指针!

c# chromium-embedded cefsharp
3个回答
5
投票

Argggh!经过更多的试验和错误,我想出来了。本网站上的一篇文章帮助我进行了调查:

https://groups.google.com/forum/#!topic/cefsharp/SflbtatvTqQ

尝试传入域的空字符串而不是“/”,或者将Url传递为“/ mywebsite”,将域传递为“192.16.1.6”

这让我想知道我的cookie params是否因为某种原因被拒绝了。我最终试图用这些参数设置cookie:

var isSet = Cef.SetCookie("http://tovalrsv01:8142/", "username", "testuser", "", "/", false, false, false, new DateTime(2020, 1, 1));

更严格地指定URL是诀窍。我猜DNS别名有时不够好。无论如何,我将离开这篇文章以防其他CefSharpers遇到类似的情况。


1
投票

这是我在代码下面用来添加cookie的代码。

var mngr = Cef.GetGlobalCookieManager();
Cookie Ac = new Cookie();
Ac.Name = "<Cookie Name>";
Ac.Value = "<Value>";
mngr.SetCookieAsync(<URL to Navigate>, Ac);

0
投票

感谢您对Akash Patel的建议。但是这个例子在我的情况下不起作用(CefSharp.OffScreen 71.0.2),所以我编辑了它:

//_browser is object of ChromiumWebBrowser
var cookieManager=_browser.RequestContext.GetDefaultCookieManager(null);
Cookie cookie = new Cookie
{
    Name = name,
    Value = value
};
cookieManager.SetCookie(url, cookie);
//or cookieManager.SetCookieAsync(url, cookie);
© www.soinside.com 2019 - 2024. All rights reserved.