部署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重用。