C#:https文件下载

今天在.net4.5环境下用WebClient下载https的文件时,报错: 基础连接已经关闭: 发送时发生错误。

加上ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;后正常。

using (WebClient client = new WebClient())
{
  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  client.DownloadFile(url, fullName);
}

 先记录一下;以后遇到其他情况再加上吧。

 附上ServicePointManager.SecurityProtocol Property参考:

ServicePointManager.SecurityProtocol Property (System.Net) | Microsoft Learn

 

如果您已经设置了TLS 1.2协议并且仍然遇到问题,那么可能是由于服务器证书不受信任或已过期。您可以尝试使用以下代码来忽略证书错误:

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

 

posted @ 2022-12-29 17:24  新*  阅读(561)  评论(0)    收藏  举报