C# System.Net.WebException: 基础连接已关闭: 发送时发生意外错误

C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send

我只在一台服务器上遇到此错误 运行 Windows Server 2003:

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


这是我的代码...有什么想法吗?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:// URL HERE ");
//request.Headers.Add("Accept", "application/xml");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.KeepAlive = false;
request.Accept = "application/xml";
request.ContentType = "application/xml; charset='UTF-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.Timeout = 10000;
request.ServicePoint.Expect100Continue = false;

当客户端计算机无法发送 HTTP 请求时会出现此问题。客户端计算机无法发送 HTTP 请求,因为连接已关闭或不可用。当客户端计算机发送大量数据时,可能会出现此问题。要解决此问题,请参阅解决方案 A、D、E、F 和 O。

https://support.microsoft.com/en-us/kb/915599

我遇到了同样的错误,在 .NET 4.5 中使用 RestSharp。我用 cURL 测试了相同的 URL 并且工作正常。经过长时间的调试,我发现设置 SecurityProtocol 解决了这个问题。

参见:"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

就我而言,我在环境之间交换 URL 时忘记从 "https" 中删除 "s"。我不小心用 https 访问了 Localhost。如果您访问没有 https 证书或过期证书的 http 站点,也会发生同样的事情。

将 HttpWebRequest.KeepAlive 设置为 false 对我不起作用。

因为我访问的是 HTTPS 页面,所以我必须将服务点安全协议设置为 Tls12。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

请注意还有其他 SecurityProtocolTypes:

SecurityProtocolType.Ssl3 
SecurityProtocolType.Tls
SecurityProtocolType.Tls11

因此,如果 Tls12 不适合您,请尝试剩下的三个选项。

另请注意,您可以设置多个协议。这在大多数情况下更可取。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

编辑:因为这是安全标准的选择,所以显然最好使用最新的(撰写本文时为 TLS 1.2),而不仅仅是做有效的事情。其实SSL3已经officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well了。来源:@aske-b

我在使用 API-KEY 从命令行手动将 nuget 包部署到 Nexus 服务器时遇到了这个错误。

我检查了nexus服务器配置,发现Nexus NuGet API-Key Realm没有激活。我已经激活它并再次尝试,一切正常。

因此,您应该检查服务器端以确认您已激活相关领域。

在这种情况下可能会出现此问题,您将要下载一个 link 过滤器 link 而您没有下载该 link 的权限。

我在尝试使用 HttpWebRequest 下载 rss 文件时遇到此错误。当我在浏览器中测试并检查响应代码时,url 没问题。 在尝试了这里的所有方法后,我想到该网站可能会根据用户代理进行阻止。

更改请求中的用户代理字符串有效:

let request = WebRequest.Create(url) :?> HttpWebRequest
request.UserAgent <- @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
let response = request.GetResponse()

此用户代理字符串来自在 Google Chrome

中键入 "what's my user agent"