Search code examples
c#asp.net-mvchttpwebrequest

"The underlying connection was closed: An unexpected error occurred on a send.". Postman goes OK with same headers


Scenario

  • Win10 x64
  • VS2013

I'm trying to make a WebRequest, but I'm getting the following error:

The underlying connection was closed: An unexpected error occurred on a send.

Digging into the inner exception, I got:

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

The code which does the request is the following:

private static Hashtable exec (String method, String uri, Object data, String contentType) {
    Hashtable response;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create (API_BASE_URL + uri);

    request.UserAgent = "MercadoPago .NET SDK v"+MP.version; //version resolves to 0.3.4
    request.Accept = MIME_JSON; // application/json
    request.Method = method; //GET
    request.ContentType = contentType; //application/json
    setData (request, data, contentType); //setData in this case does nothing.

    String responseBody = null;
    try {
      HttpWebResponse apiResult = (HttpWebResponse)request.GetResponse (); //Error throws here
      responseBody = new StreamReader (apiResult.GetResponseStream ()).ReadToEnd ();

      response = new Hashtable();
      response["status"] = (int) apiResult.StatusCode;
      response["response"] = JSON.JsonDecode(responseBody);
    } catch (WebException e) {
      Console.WriteLine (e.Message);
    }
}

What i've already done:

  • Made the request via Console Application and MVC Application controller. Both throws the same exception
  • Called the API via Postman with the exact same headers, which brings me the content correctly.

Those requests were working okay via c# about 4 days ago and I suddenly started having issues, but considering the fact that it responds okay for Postman, I can't figure out where's the problem.

Here's Postman's response

enter image description here

EDIT: Did both requests with Fiddler listening. The result for Postman shows a direct request to the API with HTTPS. When trying with my ConsoleApplication, it shows a HTTP request, which makes a tunnel to the API endpoint, port 443.

enter image description here

The TextView from Fiddler for the tunnel request says the following:

enter image description here

I noticed the "time" field which refers to a very old date, but i don't know what does it mean.


Solution

  • Figured it out. I needed to include the use of TLS1.2.

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;