How to gather all cookies using CEFSharp?

狂风中的少年 提交于 2019-12-23 20:32:48

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/41690273/how-to-gather-all-cookies-using-cefsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!