.NetCore HttpClient Proxy 设置全局代理
-
环境 .net6.0,使用的是 HttpClient
-
在Program.cs里面
service.AddHttpClient<HttpClientHelper>();
-
-
重点是在 HttpClientHelpe 的构造函数里面设置
-
构造函数会接受来自Program.cs里面注入的 HttpClient 因此我可以直接对其进行配置
-
方式一配置,全局的HttpClient的代理
-
方式二配置,当前构造函数里面的HttpClient的代理
-
完整代码如下,如有需要自行修改
-
private readonly HttpClient _httpClient;public HttpClientHelper(HttpClient httpClient1){#region Proxy //1.设置带用户和密码的代理var Address = ConfigCommon.Configuration["Proxy:Address"];//地址var Account = ConfigCommon.Configuration["Proxy:Account"];//用户名var Password = ConfigCommon.Configuration["Proxy:Password"];//密码var webProxy = new WebProxy(Address, false);webProxy.BypassProxyOnLocal = true;//2.如果有用户名和密码需要以下设置ICredentials jxCredt = new NetworkCredential(Account, Password);webProxy.Credentials = jxCredt;#region 方式一HttpClient.DefaultProxy = webProxy;#endregion#region 方式二 注释 var proxyHttpClientHandler = new HttpClientHandler{Proxy = webProxy,UseProxy = true};HttpClient httpClient = new HttpClient(proxyHttpClientHandler);_httpClient = httpClient;#endregion//超时时间设置httpClient.Timeout = TimeSpan.FromMinutes(5);//设置HeaderhttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));#endregion_httpClient = httpClient;}
-
-
-
appsettings.json里面的Proxy配置如下
-
"Proxy": {"Address": "127.0.0.1:6666","Account": "username","Password": "pwd"}
一些基本使用方法,欢迎大家讨论,转载请标明原创地址~ 谢谢~~~Bye~
-