asp.net Core HttpClient 出現Cannot access a disposed object. Object name: 'SocketsHttpHandler' 的問題。

 ASP.NET Core 部署在Centos 中 偶爾出現git

One or more errors occurred. (Cannot access a disposed object.Object name: 'SocketsHttpHandler'.)github

 以前的寫法以下:spa

  var httpclientHandler = new HttpClientHandler();
            httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
            httpclientHandler.AutomaticDecompression = DecompressionMethods.GZip;
            httpclientHandler.MaxRequestContentBufferSize = 102400;
            services.AddHttpClient("tmkhttp", option =>
            {
                option.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
                option.Timeout = new TimeSpan(0, 0, 10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return httpclientHandler;
            }); 

 

看提示應該是SocketsHttpHandler 資源釋放了,沒從新實例化。code

在github上看到一個答案 說  ConfigurePrimaryHttpMessageHandler 裏面不要直接return HttpClientHandler,要從新new 一下blog

改完後的以下:ip

 services.AddHttpClient("tmkhttp", option =>
            {
                option.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
                option.Timeout = new TimeSpan(0, 0, 10);
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler()
                {
                    MaxRequestContentBufferSize = 102400 ,
                    AutomaticDecompression = DecompressionMethods.GZip ,
                    ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true
                };
            
            }); 
相關文章
相關標籤/搜索