【发布时间】:2020-01-13 10:33:36
【问题描述】:
我正在尝试从 WEB API 加载 JSON 数据。如果我从任何浏览器请求数据,URL 工作正常。 如果我尝试使用 webClient 获取数据,则相同的 URL 不起作用。 它抛出以下错误:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +111
[IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +299
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +298
System.Net.WebClient.DownloadString(Uri address) +106
我发现这样可能会堆栈溢出类似的问题并实施了 TSL 安全协议和标头更改,但仍然无法正常工作。
下面是我的代码:
PCR IWebClientServices<PCR>.PrepareWebClient(string PreparedURL)
{
try
{
//this code bypass the SSL exception
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls;
//now we will invoke the webClient
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");
var json = webClient.DownloadString(PreparedURL);
return JsonConvert.DeserializeObject<PCR>(json);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
我被困在这里,因为这段代码有时可以正常工作,有时根本无法正常工作。 我不知道出了什么问题,但我认为在请求浏览器请求等数据时我缺少一些东西,但服务器正在捕获一些可疑的请求并且没有响应。但是,如果我从浏览器浏览 URL,它会发送数据。
【问题讨论】:
-
您是否在客户端/调用方中针对 .NET Framework 4.7.2 或更高版本,默认情况下使用 TLS 支持 1.2,当从服务器中删除对早期协议的支持时,我们遇到了类似的问题。还要在您的配置文件中强制执行此运行时
-
感谢 Schwarzie2478。是的,我的框架是 4.7.2。在这种情况下我该怎么办? web.config 有哪些变化?
标签: c# model-view-controller webclient webapi