0

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?

Percy
  • 2,855
  • 2
  • 33
  • 56
  • If code works locally, but doesn't work at deployed server, then it can be related to policy of deployed server. – Yuriy Zaletskyy Jul 11 '16 at 10:02
  • How is your service deployed? If it's self hosted the problem might be the account the service uses: https://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceaccount(v=vs.110).aspx – lavuy Jul 11 '16 at 10:09
  • I'm just testing locally at the moment. my UWP app is running locally also using a windows phone emulator. I have no information about how the web service I am calling is set up – Percy Jul 11 '16 at 10:11
  • Have you enabled basic authentication on your web server? If you're using IISExpress to test do the instructions mentioned [here](http://stackoverflow.com/questions/25642787/basic-authentication-on-iis-express). If you're using say IIS 7, use [this one](https://technet.microsoft.com/en-au/library/cc772009(v=ws.10).aspx). – akardon Jul 11 '16 at 13:46

1 Answers1

2

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?

Percy
  • 2,855
  • 2
  • 33
  • 56