Percy
Percy

Reputation: 3125

Using HttpClient in new WebApi project

I have created a new Webapi2 project and I am trying to call an external web service using this code:

WebServiceAuthResult authResult = new WebServiceAuthResult();
using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
    try
    {
        var response = await httpClient.PostAsync(url, null);

        var responseContent = await response.Content.ReadAsStringAsync();
        authResult = JsonConvert.DeserializeObject<WebServiceAuthResult>(responseContent);
    }
    catch (Exception ex)
    {
    }
}

I am getting this error:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

I have used the exact same code in a UWP project and it works perfectly - So I am guessing there's something wrong in my project set up.

I've looked at Google and other StackOverflow questions about this but they all suggest an issue with the web service - but I know this is working as I can test using my UWP project.

Can anyone suggest anything for me to try?

Upvotes: 0

Views: 147

Answers (1)

Percy
Percy

Reputation: 3125

As is usually the case with these questions the answer is a one liner but has taken 4 hours to resolve!

By adding this line of code the connection to the web service is successful:

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

I've added the code in the using statement but I think it's only required once so if anyone can tell me where is the best place to add this code and why I need it in my WebApi project and not my UWP project?

Upvotes: 2

Related Questions