Search code examples
c#httpwebrequest

HttpWebRequest call to GetResponse, fails using .net 4.5 but passes using net 4.6


We've just launched a new service, which we're having trouble connecting to from a very basic c# console app when targeting the .Net 4.5 framework.

We first found the problem in an ASP MVC site, but have broken it down into the simplest of simple console apps to help isolate the problem

Code snippet (there isn't anything else):

string myURL = @"https://<myurl>.com/<myurl>";
using (var httpClient = new HttpClient())
{                
    var request = (HttpWebRequest)WebRequest.Create(myURL);
    request.Method = "GET";
    request.ContentLength = 0;
    request.ContentType = "text/xml";

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode != HttpStatusCode.OK)
        {
            ...
        }
        else
        {
            ...
        }
    }                
}

What happens

  • Web Exception - Underlying Connection Closed.
  • Thrown on the call to GetRequest

Service Information

  • HTTPS service
  • SHA-256.

Other differences

  • Examining the request variable in the intermediate window before it is sent shows no difference.
  • Examining the request variable after the call has been attempted shows one difference - System.Net.HttpWebRequest.Pipelined is true in the successful attempt, false in the failed attempt.

Setup Essentials

  • Load balancer, balancing between two API's hosted in IIS.

Has it ever worked?

Yes!

  • If the URL is dropped into a browser - it works.
  • If I recompile this code targeting the .net 4.6 framework - it works.
  • If I connect directly to the site in IIS (over http) it works.

What am I asking

  • What could be causing this problem?
  • Have you seen similar and have suggestions for possible remedies?
  • What further steps would you take to help debug / solve the issue.
  • How would changing .Net framework version to 4.6 affect the HttpClient or the HttpWebRequest?"

Thanks, Al.


Solution

  • This is usually caused by the server using TLS v1.2. I think Net4.5 defaults to TLS v1.1, so you must add this to your code:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;