如何解决部署HttpclientHandler的正确方法
我可以知道处置Handler的正确方法是什么吗?还是我真的需要处置它? 因为Microsoft还将废弃处理程序https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler?view=netcore-3.1
这是我的静态处理程序。
private static HttpClientHandler handlerWithProxy = new HttpClientHandler
{
UseCookies = false,UseDefaultCredentials = true,DefaultProxyCredentials = CredentialCache.DefaultCredentials,Proxy = new WebProxy($"{MyProxy.ProxyHost}:{MyProxy.ProxyPort}",false),UseProxy = true,SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,ServerCertificateCustomValidationCallback = (sender,cert,chain,sslPolicyErrors) => { return true; }
};
在这里我称之为处置。正确吗?
private static async Task<JsonDocument> ResponseMessage(HttpRequestMessage request,CancellationToken token)
{
HttpCompletionOption option = HttpCompletionOption.ResponseHeadersRead;
using (HttpResponseMessage response = MyProxy.UseProxy ? await clientWithProxy.SendAsync(request,option,token).ConfigureAwait(false)
: await client.SendAsync(request,token).ConfigureAwait(false))
{
token.ThrowIfCancellationRequested();
HttpStatusCode status = response.StatusCode;
using (Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
if (stream == null || stream.CanRead == false) { return default; }
var options = new JsonDocumentOptions { AllowTrailingCommas = true };
var json = await JsonDocument.ParseAsync(stream,options).ConfigureAwait(false);
if (!response.IsSuccessStatusCode) { throw new InvalidDataException($"Error occured: {ParseError(uri,json,status)}"); }
//is this right of calling the dispose if it is already null?
if (handler == null) { handler.Dispose(); }
return json;
}
}
}
解决方法
这个答案很简短,但是很贴切:
处理程序在创建时与HttpClient
绑定。您不处理这些。只需使用它创建您的HttpClien
t并忽略它。 MS网站上的示例不是典型的使用场景。
请确保在创建HttpClient
时将其设置为静态并且在类范围内:
private static readonly HttpClient clientWithProxy = new HttpClient(handlerWithProxy);
您应在应用程序的整个生命周期中对所有HTTP请求使用相同的HttpClient
重用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。