Http Client An existing connection was forcibly closed by the remote host

Viewed 7310

What am I doing wrong here?

        var formContent = new FormUrlEncodedContent(new[]
            {
            new KeyValuePair<string, string>("mobile_numbers", "5555555555"), 
            new KeyValuePair<string, string>("message", "Whoo hahahahah") 
            });           

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("https://api.iwin.co.za");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "134134134");
        HttpResponseMessage response = client.PostAsync("iwin/api/v1/messages", formContent).Result;

When I run code above I get this error: An existing connection was forcibly closed by the remote host I went over the code a few times and everything looks fine, some articles suggest the error I'm getting is a server issue but when i try with R-client it works fine

Http request

2 Answers

This can be caused if the client and server can't agree on a version of the TLS protocol to use.

I think it's the case that .Net 4.5.2 and earlier default to v1, with v1.2 deactivated if it's included in the framework. (In .Net 4.6.*, v1.2 is the default.)

To enable v1.2 in 4.5.2 you can use:

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

(I believe this enables it for the whole application domain?)

Solved the issue (against a different website) for me, anyway.

Related