letsc
letsc

Reputation: 2115

HttpClient unable to handshake with an HTTPs endpoint

I have a requirement to get data from an API endpoint from inside my WebAPI controller. I am using HttpClient to achieve the goal. However, it seems the client is unable to fetch data from the endpoint. The connect call fails with the below error:

 HTTPS handshake to test.site failed. System.IO.IOException Unable to read  
 data from the transport connection: An existing connection was forcibly  
 closed by the remote host. <An existing connection was forcibly closed by 
 the remote host>

The API endpoint is hosted properly with a valid SSL cert. Moreover, if I use a console app / use postman to hit the API, there is no error and I can see the response. However, when I try to hit the same API in exactly the same manner from inside my API controller, I see the SSL connection error.

Here's the code for the client:

HttpClient client = new HttpClient()
        {
            BaseAddress = new Uri(uri)
        };

var requestMessage = new HttpRequestMessage(                                
                         new HttpMethod("GET"),
                         requestUrl);

ServicePointManager.ServerCertificateValidationCallback += 
                                (sender, certificate, chain, sslPolicyErrors) => true;

client.DefaultRequestHeaders.Add(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

var responseMessage = await client.SendAsync(requestMessage);

Why is the behavior different for the connect request from the WebAPI as compared to a console app? Can you help me fix the above issue?

Upvotes: 2

Views: 2186

Answers (1)

jpishko
jpishko

Reputation: 1070

Older versions of the .NET framework default to using older versions of TLS which may get rejected by the endpoint. It is becoming standard to reject requestd using less than TLS v1.2.

To get around this you can either use a newer version of the .NET framework or you may be able to explicitly set which version(s) of TLS the ServicePointManager uses.

Upvotes: 3

Related Questions