C# 解决 https请求 ssl证书问题,看我一篇通通解决

废话不多说,直接上代码,实干兴邦,空谈误国!光说不贴源代码更是耍流氓!

针对旧版本的接口框架,.netformwork4.5以下,加上传统的ssl机制即可解决问题。

针对.net core版本的框架,采用ssl证书验证回调的方式,其中方案二和方案三同属于一种解决方式,方案三的更直接明了。

代码实测的框架分别为netformwork4.5、.net core3.1,完美解决问题。如有纰漏,欢迎各路大神不吝赐教,多多交流分享哈。


//ssl证书请求无效的问题解决方案
//********
//方案一,netformwork
 //关于ServicePointManager.SecurityProtocol的设置是解决问题的关键。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 
    | SecurityProtocolType.Tls12 
    | SecurityProtocolType.Tls11 
    | SecurityProtocolType.Tls;
//上述代码放在请求之前
HttpWebRequest request = (HttpWebRequest)WebRequest.Create
("https://www.baidu.com");
request.Timeout = 15000;
request.ReadWriteTimeout = 20000;
request.KeepAlive = true;

//********
//方案二
private static bool RemoteCertificateValidate
(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
	return true;
}
ServicePointManager.ServerCertificateValidationCallback 
+= RemoteCertificateValidate;
//上述代码放在请求之前
HttpWebRequest request = (HttpWebRequest)WebRequest.Create
("https://www.baidu.com");
request.Timeout = 15000;
request.ReadWriteTimeout = 20000;
request.KeepAlive = true;

//********
//方案三,.net core 3.1
//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);
//上述代码放在请求之前
HttpWebRequest request = (HttpWebRequest)WebRequest.Create
("https://www.baidu.com");
request.Timeout = 15000;
request.ReadWriteTimeout = 20000;
request.KeepAlive = true;

你可能感兴趣的:(.net,core,前端和接口,.netcore,ssl证书,c#,https)