方法1:
CefSharp.CefSharpSettings.Proxy = new CefSharp.ProxyOptions("ip", "端口号", "用户名", "密码");
这种方法的缺点是无法动态改变代理IP。
方法2:在程序运行期间,动态修改代理IP
ChromiumWebBrowser wb = new ChromiumWebBrowser("https://www.baidu.com/"); wb.RequestHandler = new MyRequestHandler("rsel", "xanz"); public class MyRequestHandler : DefaultRequestHandler { string _proxyUserName = "", _proxyUserPwd = ""; public MyRequestHandler() { } public MyRequestHandler(string proxyUser,string proxyPwd) { _proxyUserName = proxyUser; _proxyUserPwd = proxyPwd; } public 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(_proxyUserName, _proxyUserPwd); return true; } return false; } } async private void SetProxy(ChromiumWebBrowser cwb, string address) { await Cef.UIThreadTaskFactory.StartNew(delegate { var rc = cwb.GetBrowser().GetHost().RequestContext; Dictionary<string, string> v = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(address)) { v["mode"] = "fixed_servers"; v["server"] = address; } else v["mode"] = "direct";//设为direct表示取消代理 string error; bool success = rc.SetPreference("proxy", v, out error); }); } 需要设置/取消代理的时候,调用SetProxy方法即可。