从 https URL 下载文件时出现 WebClient 错误 [英] WebClient error when downloading file from https URL
问题描述
尝试从 https URL (https://nvd.nist.gov/download/nvd-rss.xml)
此 URL 可通过浏览器公开访问.
在控制台项目中使用 C# Webclient.
但得到如下异常
using (WebClient client = new WebClient()){System.Net.ServicePointManager.SecurityProtocol =System.Net.SecurityProtocolType.Ssl3;client.DownloadFile(uri, @c: est
vd-rss.xml");}
<块引用>
$exception {底层连接已关闭:发送时发生意外错误."} System.Net.WebException
尝试将 SSL 等所有属性添加到 system.Net,但没有帮助.
原因是有问题的站点仅支持 TLS 1.2.在 .NET 中,System.Net.ServicePointManager.SecurityProtocol
的默认值为 Ssl
|Tls
,表示.NET客户端默认不支持Tls 1.2(SSL协商时在支持协议列表中没有列出该协议).至少许多 .NET Framework 版本都是这种情况,不确定是否适用于所有版本.但是 .NET 确实支持 TLS 1.2,要启用它,您应该这样做:
string uri = "https://nvd.nist.gov/download/nvd-rss.xml";使用 (WebClient 客户端 = new WebClient()){System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;client.DownloadFile(uri, @"c: est
vd-rss.xml");}
你应该没事的.当然,最好支持多个 TLS 1.2 协议,因为 System.Net.SecurityProtocolType 是一个全局设置,并非所有站点都支持 TLS 1.2:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls |System.Net.SecurityProtocolType.Tls11 |System.Net.SecurityProtocolType.Tls12;
Trying to download xml file from https URL (https://nvd.nist.gov/download/nvd-rss.xml)
This URL is openly accessible through browser.
Using C# Webclient with console project.
But getting Exception as below
using (WebClient client = new WebClient())
{
System.Net.ServicePointManager.SecurityProtocol =
System.Net.SecurityProtocolType.Ssl3;
client.DownloadFile(uri, @"c: est
vd-rss.xml");
}
$exception {"The underlying connection was closed: An unexpected error occurred on a send."} System.Net.WebException
Tried adding all properties like SSL etc to system.Net, but did not help.
The reason is site in question supports only TLS 1.2. In .NET, default value for System.Net.ServicePointManager.SecurityProtocol
is Ssl
| Tls
, which means that .NET client by default does not support Tls 1.2 (it does not list this protocol in the list of supported protocols during SSL negotiation). At least this is the case for many .NET Framework versions, not sure if for all. But .NET really do support TLS 1.2, and to enable it you should just do:
string uri = "https://nvd.nist.gov/download/nvd-rss.xml";
using (WebClient client = new WebClient())
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
client.DownloadFile(uri, @"c: est
vd-rss.xml");
}
And you should be fine. Of course it's better to support more than one TLS 1.2 protocol, because System.Net.SecurityProtocolType is a global setting and not all sites support TLS 1.2:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
这篇关于从 https URL 下载文件时出现 WebClient 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!