und*_*god 9 c# asp.net-mvc httpwebrequest
脚本
我正在尝试创建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)
我已经做了什么:
大约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)
像这样启用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)
弄清楚了。我需要包含 TLS1.2 的使用。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2728 次 |
最近记录: |