"基础连接已关闭:发送时发生意外错误." 邮递员用相同的标题行

und*_*god 9 c# asp.net-mvc httpwebrequest

脚本

  • Win10 x64
  • VS2013

我正在尝试创建WebRequest,但是我收到以下错误:

底层连接已关闭:发送时发生意外错误.

挖掘内部异常,我得到:

"无法从传输连接读取数据:远程主机强行关闭现有连接."

执行请求的代码如下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经做了什么:

  • 通过控制台应用程序和MVC应用程序控制器发出请求.两者都抛出相同的异常
  • 通过Postman使用完全相同的标题调用API,这正确地为我带来了内容.

大约4天前,这些请求通过c#正常工作,我突然开始遇到问题,但考虑到它对Postman的反应很好,我无法弄清楚问题出在哪里.

这是邮递员的回应

在此输入图像描述

编辑:两个请求与提琴手听.Postman的结果显示了使用HTTPS直接请求API.尝试使用我的ConsoleApplication时,它会显示一个HTTP请求,该请求会建立到API端点(端口443)的隧道.

在此输入图像描述

来自Fiddler的隧道请求的TextView说明如下:

在此输入图像描述

我注意到"时间"字段指的是一个非常古老的日期,但我不知道它是什么意思.

小智 6

您可以尝试以下代码:

string url = ""; // url of the endpoint

WebClient client = new WebClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
client.Encoding = Encoding.UTF8;
client.Headers.Add("content-type", "application/json"); // same as other parameters in the header

var data = client.DownloadString(url);
Run Code Online (Sandbox Code Playgroud)


kam*_*eet 6

像这样启用Tls12是一种不好的做法 -

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)

将来,如果您需要使用更高版本的TLS,则必须更新代码.

如果您使用的是旧版本的.NET,则只需将其更高版本切换为默认启用Tls12的版本.

例如,web.config中的这个简单更改将自动启用Tls12-

<httpRuntime targetFramework="4.6.1"/>
Run Code Online (Sandbox Code Playgroud)


und*_*god 5

弄清楚了。我需要包含 TLS1.2 的使用。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)


Wes*_*sam 5

(作为具有相同问题的其他人的参考)这也可能是双跳问题的结果,您应该将记入用户(在池中)传递到传递服务器或从一个环境传递到另一个环境,否则用户设置为“匿名/用户”,您将收到“现有连接被远程主机强制关闭”。错误