C# – HttpClient with .Net Core 2.1 hangs

.net core.net-core-2.1asp.net-core-2.1cnet

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

Best Answer

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);
Related Topic