C# 解决请求被中止:无法建立SSL / TLS安全通道问题

时间:2023-03-10 05:07:51
C# 解决请求被中止:无法建立SSL / TLS安全通道问题
在网上查了很多资料,基本是这么一个思路:
在通过
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
HttpWebResponse sp = (HttpWebResponse)req.GetResponse();
作处理时,有些输入有些URL会在
HttpWebResponse sp = (HttpWebResponse)req.GetResponse();
的时候抛出一个“基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系”的异常。
最简单的办法是:
,先加入命名空间:
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
,再重载CheckValidationResult方法,返回true
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
,然后在HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
前面加上如下几行代码:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificatidationCallback = new System.Net.Security.RemoteCertificatidationCallback(CheckValidationResult);//验证服务器证书回调自动验证

此时我发现问题可以解决,但是有一个问题是这种方法在在 .net 4.5以上是没问题的,因为如下:

v4.0

#region 程序集 System.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll
#endregion using System; namespace System.Net
{
// 摘要:
// 指定 Schannel 安全包支持的安全协议。
[Flags]
public enum SecurityProtocolType
{
// 摘要:
// 指定安全套接字层 (SSL) 3.0 安全协议。
Ssl3 = ,
//
// 摘要:
// 指定传输层安全 (TLS) 1.0 安全协议。
Tls = ,
}
}
v4.5
#region 程序集 System.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.dll
#endregion using System; namespace System.Net
{
// 摘要:
// 指定 Schannel 安全包支持的安全协议。
[Flags]
public enum SecurityProtocolType
{
// 摘要:
// 指定安全套接字层 (SSL) 3.0 安全协议。
Ssl3 = ,
//
// 摘要:
// 指定传输层安全 (TLS) 1.0 安全协议。
Tls = ,
//
Tls11 = ,
//
Tls12 = ,
}
}

假如在.net 4.0上使用如下代码时一样报错

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

此时我想在.net 4.0或者以下版本使用上面的方法就不可行,那么怎么办?

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType) | (SecurityProtocolType) | (SecurityProtocolType);
ServicePointManager.ServerCertificatidationCallback = new System.Net.Security.RemoteCertificatidationCallback(CheckValidationResult);//验证服务器证书回调自动验证

虽然.net 4.0 SecurityProtocolType 枚举中没有 Tls11 和Tls12 两种类型那么我们只能强转!!!!!