HttpClient with .Net Core 2.1 hangs

本秂侑毒 提交于 2019-12-21 07:36:50

问题


Given the following .Net Core 2.1 Console App...

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;

namespace TestHttpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                    

                    string url = "https://jsonplaceholder.typicode.com/posts/1";
                    var response = httpClient.GetAsync(url).Result;
                    string jsonResult = response.Content.ReadAsStringAsync().Result;   
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
    }
}

The call to GetAsync hangs throwing an exception with the following message:

System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

However, switch to .Net Core 2.0 and it works fine...

NOTE

I've tried using:

HttpClientFactory -> Same result
WebRequest        -> Same result

Thoughts?

UPDATE 1 This works when not on the corporate network which might mean a change in behavior with the proxy perhaps. However, core2.0 still works regardless so trying to find the difference.

UPDATE 2 Looks like a bug was introduced and it is reported...

https://github.com/dotnet/corefx/issues/30166#issuecomment-395489603


回答1:


The was a change in CoreFx 2.1 that causes the HttpClient to use a new HttpClientHandler. This is possibly the cause of your problem and why downgrading works.

There are many ways to reset the handler and you can read more about it in the change log. You can use the old HttpHandler by instantiating an HttpClient with a WinHttpHandler as the parameter, setting the environment variable DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER to false, or by calling the following in your code:

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);



回答2:


So apparently there is a bug/breaking change reported on this.

Here: https://github.com/dotnet/corefx/issues/30166 https://github.com/dotnet/corefx/issues/30191

Two separate but related issues that I believe is what I am experiencing.

However, I found what appears to be a workaround.

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace TestHttpClient
{
    static class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                using (var httpClient = new HttpClient(new WinHttpHandler() { WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy }))
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    string url = "https://jsonplaceholder.typicode.com/posts/1";                   

                    var response = await httpClient.GetAsync(url);
                    string jsonResult = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                throw;
            }
        }
    }
}

The key part here is to use WinHttpHandler and set the WindowsProxyUsePolicy to WindowsProxyUsePolicy.UseWinInetProxy

WinHttpHandler is found by adding nuget package System.Net.Http.WinHttpHandler




回答3:


This is a famous "21 seconds" timeout problem... What helps in Azure for service with rare calls (my service is calling external service from Azure infrastructure) is adding:

httpClient.DefaultRequestHeaders.ConnectionClose = true;


来源:https://stackoverflow.com/questions/50749042/httpclient-with-net-core-2-1-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!