【SSL】WebClient 请求 https 页面出错:未能创建 SSL/TLS 安全通道

时间:2021-08-04 15:40:43

#问题:

  当向一个https的url上发送请求,报错:未能创建 SSL/TLS 安全通道;

using (WebClient client = new WebClient())
{
string address="https://xxx.com";
client.Headers.Add(HttpRequestHeader.ContentType, "text/xml"); System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
var response = client.UploadData(address, "POST", encoding.GetBytes(msg));
}

#原因:

  ssl证书不受信任,验证失败;

#解决方案:

  请求之前,进行如下设置;

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);

private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}

  简写

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

  整合

 public class Test
{
public void TestFun
{
5       ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
       using (WebClient client = new WebClient())
      {
      string address="https://xxx.com";
        client.Headers.Add(HttpRequestHeader.ContentType,"text/xml");
      System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
      var response = client.UploadData(address, "POST", encoding.GetBytes(msg));
      }
}
private bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{ // 总是接受 认证平台 服务器的证书
return true;
}
}