C# WebClient调用DownloadString下载HTTPS资源时报连接关闭与认证失败异常
报错原因
- 你访问的
https://www.nndc.bnl.gov站点已经彻底禁用SSL 3.0、TLS 1.0、TLS 1.1这些老旧加密协议,仅支持TLS 1.2及以上版本。如果你使用的是.NET Framework 4.5或更早的运行时,WebClient默认启用的加密协议列表和站点要求不匹配,TLS握手阶段就会被远程服务器主动关闭传输流,最终抛出你遇到的“基础连接已关闭”“身份验证失败”异常。 - 除此之外,
WebClient默认发送的是IE6时代的老旧User-Agent标识,很容易被站点的WAF(Web应用防护)规则拦截,直接中断连接。
解决步骤
1. 全局启用TLS 1.2支持
必须在所有网络请求发起前,也就是Main方法的最开头添加如下配置,强制运行时使用TLS 1.2:
// 需先引入命名空间 using System.Net; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
如果需要兼容其他老旧服务,可以同时保留多协议配置:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
2. 给WebClient添加合法请求头
初始化WebClient实例后,添加模拟现代浏览器的User-Agent头,避免被站点防护拦截:
myWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
完整修改后的代码
class Program { // URI模式: https://www.nndc.bnl.gov/nudat2/decaysearchdirect.jsp?nuc=235U&unc=nds static string baseUri = "https://www.nndc.bnl.gov/nudat2/decaysearchdirect.jsp?nuc="; static string destFolder = @".\Downloaded Files\"; // 创建WebClient实例。 static WebClient myWebClient = new WebClient(); static XElement isotopes = XElement.Load(@"..\..\..\..\MakeDecayChainLinks\MakeDecayChainLinks\bin\Debug\isotopes2.xml"); static StreamWriter sr = new StreamWriter("Log.rtf"); static void Main(string[] args) { // 新增:配置TLS协议支持 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // 新增:添加浏览器标识请求头 myWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"); foreach (XElement e in isotopes.Elements().Reverse()) { string isotopeName = e.Attribute("AtomicWeight").Value + e.Attribute("Symbol").Value.ToUpper(); string uri = baseUri + isotopeName + "&unc=nds"; string destFile = destFolder + isotopeName + ".txt"; try { string content = myWebClient.DownloadString(uri); // 此处原调用逻辑无需修改 using (StreamWriter sw = new StreamWriter(destFile)) sw.Write(content); sr.WriteLine(isotopeName + " downloaded\nURI: " + uri); } catch (Exception ex) { sr.WriteLine(isotopeName + " NOT FOUND: " + ex.Message + "\nURI: " + uri); }; Console.WriteLine(uri); } sr.Close(); Console.ReadKey(); } }
补充说明:如果使用的是.NET Core/.NET 5+版本,
WebClient默认已经启用TLS 1.2,此时仅需添加User-Agent请求头即可解决问题。另外WebClient在新版.NET中已标记为过时,新开发的项目推荐使用HttpClient实现网络请求。
内容的提问来源于stack exchange,提问作者UserX
相关产品推荐
相关产品推荐

