gpt4 book ai didi

c# - "The underlying connection was closed: An unexpected error occurred on a send."。 postman 可以使用相同的标题

转载 作者:太空狗 更新时间:2023-10-29 17:35:38 28 4
gpt4 key购买 nike

场景

  • Win10 x64
  • VS2013

我正在尝试发出 WebRequest,但出现以下错误:

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

深入研究内部异常,我得到:

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

执行请求的代码如下:

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);
}
}

我已经做了什么:

  • 通过控制台应用程序和 MVC 应用程序 Controller 发出请求。两者都抛出相同的异常
  • 使用完全相同的 header 通过 Postman 调用 API,这为我提供了正确的内容。

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

这是 postman 的回应

enter image description here

编辑: Fiddler 监听了两个请求。 Postman 的结果显示了使用 HTTPS 对 API 的直接请求。当尝试使用我的 ConsoleApplication 时,它显示了一个 HTTP 请求,它建立了一个到 API 端点、端口 443 的隧道。

enter image description here

来自 Fiddler 的隧道请求的 TextView 如下所示:

enter image description here

我注意到“时间”字段指的是一个很旧的日期,但我不知道它是什么意思。

最佳答案

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

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

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

如果您使用的是旧版本的 .NET,您可以简单地将其切换到默认启用 Tls12 的更高版本。

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

<httpRuntime targetFramework="4.6.1"/>

关于c# - "The underlying connection was closed: An unexpected error occurred on a send."。 postman 可以使用相同的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905223/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com