【问题标题】:WebClient error when downloading file from https URL从 https URL 下载文件时出现 WebClient 错误
【发布时间】:2017-01-11 11:19:56
【问题描述】:

尝试从 https URL (https://nvd.nist.gov/download/nvd-rss.xml) 下载 xml 文件

此 URL 可通过浏览器公开访问。

在控制台项目中使用 C# Webclient。

但得到如下异常

using (WebClient client = new WebClient())
{
        System.Net.ServicePointManager.SecurityProtocol =
            System.Net.SecurityProtocolType.Ssl3;
        client.DownloadFile(uri, @"c:\test\nvd-rss.xml");
}

$exception {“底层连接已关闭:发送时发生意外错误。”} System.Net.WebException

尝试将 SSL 等所有属性添加到 system.Net,但没有帮助。

【问题讨论】:

    标签: c# https console-application webclient downloadfile


    【解决方案1】:

    原因是相关站点仅支持 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";
    using (WebClient client = new WebClient())
    {
         System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
         client.DownloadFile(uri, @"c:\test\nvd-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;
    

    【讨论】:

    • 感谢您的解决方案和解释。这很完美。
    【解决方案2】:

    .NET 4.0。不支持 TLS 1.2,但如果您在系统上安装了 .NET 4.5(或更高版本),那么即使您的应用程序框架不支持,您仍然可以选择使用 TLS 1.2。唯一的问题是 .NET 4.0 中的 SecurityProtocolType 没有 TLS1.2 的条目,所以我们必须使用这个枚举值的数字表示:

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
    

    【讨论】:

      【解决方案3】:

      试试这个:

      using (HttpClient client = new HttpClient())
      {
            var response = await client.GetAsync("https://nvd.nist.gov/download/nvd-rss.xml");
      
            string xml = await response.Content.ReadAsStringAsync();
            //or as byte array if needed
            var xmlByteArray = await response.Content.ReadAsByteArrayAsync();
            //or as stream
            var xmlStream = await  response.Content.ReadAsStreamAsync();
      
            //write to file
             File.WriteAllBytes(@"c:\temp\test.xml", xmlByteArray)
      
       }
      

      【讨论】:

      • 感谢您的回复。试过这个,但这没有触发任何请求或收到任何响应。也在提琴手中验证。 var response = await client.GetAsync("nvd.nist.gov/download/nvd-rss.xml");
      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2017-03-09
      • 1970-01-01
      相关资源
      最近更新 更多