C# 请求被中止: 未能创建 SSL/TLS 安全通道。 设置SecurityProtocol无效
C# 请求被中止: 未能创建 SSL/TLS 安全通道。 设置SecurityProtocol无效
今天为了获取一张图片,用了一段代码:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((a, b, c, d) => true);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = false;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(imgUrl);
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.Method = "GET";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
里面添加了ServicePointManager.SecurityProtocol,但是一直还是报错:"请求被中止: 未能创建 SSL/TLS 安全通道。"
感觉非常奇怪,然后通过DevTools看了一下图片网址的协议版本:
发现版本已经到了TLS 1.3了,因为我本地的版本是.net framework 4.7 ,还没有支持Tls1.3版本,于是修改了ServicePointManager.SecurityProtocol:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | (SecurityProtocolType)12288;
结果换了新的报错:不支持请求的安全协议。
网上说只有最新的.net 5里面才支持了Tls1.3版本,那.net framework系列就没有解决办法了吗?
C#
.NET40兼容,默认框架越新集成的TLS协议版本就越高,最新最安全的是TLS1.3版本。
[SecurityCritical]
[SecuritySafeCritical]
private static void InitialSecurityProtocol()
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| (SecurityProtocolType)0x300 // Tls11
| (SecurityProtocolType)0xC00 // Tls12
| (SecurityProtocolType)0x3000; // Tls13
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| (SecurityProtocolType)0x300 // Tls11
| (SecurityProtocolType)0xC00; // Tls12
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| (SecurityProtocolType)0x300; // Tls11
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls;
}
catch (Exception) { }
}
}
}
}
解决C#中WebClient不能下载https内容问题
在下载代码之前加入如下代码:
// 解决WebClient不能通过https下载内容问题
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // **** Always accept
};
上述代码主要是为了跳过https的ssl验证。