【SSL】WebClient 請求 https 頁面出錯:未能創建 SSL/TLS 安全通道


 

#問題:

  當向一個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; };

  整合

 1 public class Test
 2 {
 3     public void TestFun
 4     {
 5       ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
 6        using (WebClient client = new WebClient())
 7       {
 8           string address="https://xxx.com";
9         client.Headers.Add(HttpRequestHeader.ContentType,"text/xml"); 10       System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding(); 11       var response = client.UploadData(address, "POST", encoding.GetBytes(msg)); 12       } 13 } 14 private bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) 15 { // 總是接受 認證平台 服務器的證書 16 return true; 17 } 18 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM