为了使用WebClient而不是Chrome进行下载,我拦截了一个下载网址。然后我在使用访问者获取Cookie时遇到问题。我陷入的陷阱是我不明白访问者是异步运行的,因此只有30%的案例得到了正确的结果,过早地访问了收集的cookie。
当我搜索很长时间以寻找解决方案时,我想在此处粘贴我在演示代码中找到的那个。
答案 0 :(得分:3)
这是我找到的代码。 等待关键字是我失踪的重要部分:
class CookieCollector : ICookieVisitor
{
private readonly TaskCompletionSource<List<Cookie>> _source = new TaskCompletionSource<List<Cookie>>();
public bool Visit(Cookie cookie, int count, int total, ref bool deleteCookie)
{
_cookies.Add(cookie);
if (count == (total - 1))
{
_source.SetResult(_cookies);
}
}
// https://github.com/amaitland/CefSharp.MinimalExample/blob/ce6e579ad77dc92be94c0129b4a101f85e2fd75b/CefSharp.MinimalExample.WinForms/ListCookieVisitor.cs
// CefSharp.MinimalExample.WinForms ListCookieVisitor
public Task<List<Cookie>> Task => _source.Task;
public static string GetCookieHeader(List<Cookie> cookies)
{
StringBuilder cookieString = new StringBuilder();
string delimiter = string.Empty;
foreach (var cookie in cookies)
{
cookieString.Append(delimiter);
cookieString.Append(cookie.Name);
cookieString.Append('=');
cookieString.Append(cookie.Value);
delimiter = "; ";
}
return cookieString.ToString();
}
private readonly List<Cookie> _cookies = new List<Cookie>();
public void Dispose()
{
}
}
// usage:
void foo()
{
var cookieManager = Cef.GetGlobalCookieManager();
var visitor = new CookieCollector();
cookieManager.VisitUrlCookies(targetUrl, true, visitor);
var cookies = await visitor.Task; // AWAIT !!!!!!!!!
var cookieHeader = CookieCollector.GetCookieHeader(cookies);
}