HttpClient Error: An existing connection was forcibly closed by the remote host

Problem

I am calling a HTTP endpoint using the HttpClient and I receive this error: 

An error occurred while sending the request.  Inner Exception: An existing connection was forcibly closed by the remote host.

So this is why it’s a problem.  I know my code WORKS.  It works in many other projects, but it’s not working in this one.  

One more thing: the endpoint it’s calling is an Azure Function, so it’s HTTPS

Here’s my code:

        public RestApiHelper(string baseAddress)
        {
            this.client = new HttpClient { BaseAddress = new Uri(baseAddress) };
        }

        public async Task<string> HttpPost(string url, string payload)
        {
            var response = await this.client.PostAsync($"{url}", new StringContent(payload, Encoding.UTF8, "application/json"));
            ...
        }

Solution

Enable support for TLS 1.2.

Here’s my corrected code:

        public async Task<string> HttpPost(string url, string payload)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            var response = await this.client.PostAsync($"{url}", new StringContent(payload, Encoding.UTF8, "application/json"));

            ...
        }

Discussion

When the code worked without setting the SecurityProtocol, it was running in projects targeting .NET 4.6.1.  The code that was failing was targeting .NET 4.5.  It seems that .NET 4.5 enables SSL3 and TLS 1.0 by default and .NET 4.6.1 enables TLS 1.2.  I’m not 100% if that’s exactly correct, but it doesn’t really matter.  It seems that Azure Functions has disabled SSL3 and TLS1.0, which is a good thing.  Anyway, it’s interesting to note that upgrading my project from .NET 4.5 to .NET 4.6.1 did NOT fix the issue.  I still had to set the SecurityProtocol manually.  For what it’s worth, the legacy project is a WCF app.

Reference

Thanks to Paul Pearce for his Stack Overflow answer to a similar question.

I hope this helps someone!

Happy coding,

Tom Hundley
Elegant Software Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s