如何使用CEFSharp收集所有cookie? [英] How to gather all cookies using CEFSharp?
问题描述
为了使用WebClient而不是Chrome进行下载,我拦截了一个下载URL。然后,我在使用访问者获取Cookie时遇到了问题。我陷入的陷阱是我不了解访问者是异步运行的,因此只有30%的案例获得了正确的结果,太早访问收集的cookie。
In order to do a download using WebClient not Chrome, I intercepted a download URL. Then I had problems fetching cookies using a visitor. The pitfall I fell in was that I did not understand that the visitor is running asynchronously and therefore only in 30% of the cases got the correct result accessing the collected cookies too early.
当我寻找一个解决方案很长时间时,我想将在演示代码中找到的解决方案粘贴到这里。
As I search quite long for a solution I would like to paste the one I found in the demo code here.
推荐答案
这是我找到的代码。 await 关键字是我缺少的重要部分:
This is the code I found. The await key word is the vital piece I was missing:
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);
}
这篇关于如何使用CEFSharp收集所有cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!