C# Cefsharp 设置代理方法

前提条件

为了实现在cefsharp里面设置代理,首先在创建一个ChromiumWebBrowser的时候,检查是否使用了以下代码

settings.CefCommandLineArgs.Add("no-proxy-server", "1");//不使用代理

在RequestHandler下,实现GetAuthCredentials

public class BaseRequestHandler : RequestHandler
{
    private string _userName;
    private string _password;

    public BaseRequestHandler(string userName, string password)
    {
        this._userName = userName;
        this._password = password;
    }

    public BaseRequestHandler()
    {
        
    }

  

    protected override bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host,
        int port, string realm, string scheme, IAuthCallback callback)
    {
        if (isProxy == true)
        {
            callback.Continue(_userName, _password);

            return true;
        }

        return false;
    }
}

 

增加/卸载代理

万事俱备后,在对应的地方加上。如果想卸载掉代理, v["mode"] = "direct"; 替换即可

private async Task SetProxy(ChromiumWebBrowser cwb, string address)
{
    try
    {
        await Cef.UIThreadTaskFactory.StartNew(delegate
        {
            var rc = cwb.GetBrowser().GetHost().RequestContext;
            var v = new Dictionary<string, object>();
            v["mode"] = "fixed_servers";
            v["server"] = address;
            string error;
            bool success = rc.SetPreference("proxy", v, out error);
            Console.WriteLine(success);
        });
    }
    catch (Exception e)
    {
        //
    }
}

 

posted @ 2021-09-20 14:45  樱花落舞  阅读(477)  评论(0编辑  收藏  举报