search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C# HttpWebRequest 無法建立 SSL/TLS 的安全通道 – jashliao部落格

C# HttpWebRequest 無法建立 SSL/TLS 的安全通道

 

資料來源: https://hk.saowen.com/a/196b225c08d7a25db894d8c0d2176e3039224550172e90de7c8adaefc3e13ff6
 

在網上查了很多資料,基本是這麼一個思路:

在通過
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = “GET”; 
HttpWebResponse sp = (HttpWebResponse)req.GetResponse();
作處理時,有些輸入有些URL會在
HttpWebResponse sp = (HttpWebResponse)req.GetResponse();
的時候拋出一個“基礎連接已經關閉: 未能為 SSL/TLS 安全信道創建信任關係”的異常。
最簡單的辦法是:

 

1,先加入命名空間:
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

 

2,再重載CheckValidationResult方法,返回true
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {  return true; }

 

3,然後在HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
前面加上如下幾行代碼:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificatidationCallback = new System.Net.Security.RemoteCertificatidationCallback(CheckValidationResult);//驗證服務器證書回調自動驗證



熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦