c# - 将 HttpClientHandler 添加到 HttpClient 全局静态变量
问题描述
有人可以帮助我吗?如何将 HttpClientHanlder 添加到 HttpClient 全局变量中?有人说我做错了总是为每个请求创建一个新的 httpclient。
如果我这样尝试:
//global variable
// the handler isn't working
private static HttpClient client = new HttpClient(addHandlers());
private static HttpClientHandler addHandlers()
{
return new HttpClientHandler()
{
UseProxy = Proxy.IsUseProxy ? true : false,
Proxy = Proxy.IsUseProxy ? new WebProxy($"{Proxy.ProxyHost}:{Proxy.ProxyPort}") : null,
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; },
// SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
};
}
在这里我提出我的要求
public static async Task<JsonDocument> ParseJsonData(string api, CancellationToken ct)
{
client = new HttpClient(addHandlers()); //this is might my wrong doing? re-creating every request.
var uri = new Uri(api, UriKind.Absolute);
using (var request = new HttpRequestMessage(HttpMethod.Get, uri))
{
/// etc..
}
}
更新修复:
private static HttpClientHandler addHandlers = new HttpClientHandler
{
UseProxy = Proxy.UseProxy,
Proxy = Proxy.UseProxy ? new WebProxy($"{Proxy.ProxyHost}:{Proxy.ProxyPort}") : null,
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
};
private static HttpClient client = new HttpClient(addHandlers);
解决方案
private static HttpClient = new HttpClient(addHandlers());
这不是有效的代码。您实际上需要为静态字段命名:
private static HttpClient client = new HttpClient(addHandlers());