1. 程式人生 > 實用技巧 >C# 未能建立 SSL/TLS 安全通道 和C# 基礎連線已經關閉: 傳送時發生錯誤. 解決方案

C# 未能建立 SSL/TLS 安全通道 和C# 基礎連線已經關閉: 傳送時發生錯誤. 解決方案

原因應該是,介面方變更了安全協議,而客戶端並未啟用該協議。解決辦法自然就是:讓客戶端啟用該協議。具體就是在發起網路請求之前確保ServicePointManager.SecurityProtocol中含有服務端所用的安全協議,如果不知道或希望客戶端健壯一點,當然最簡單的方式就是把所有可用的協議都啟用,隨你服務端將來怎麼換。程式碼如下:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                       | SecurityProtocolType.Tls
                                       | SecurityProtocolType.Tls11
                                       | SecurityProtocolType.Tls12;

但如果客戶端是基於.net framework 4.0,SecurityProtocolType列舉中並沒有Tls11和Tls12,這就需要直接填值:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                       | SecurityProtocolType.Tls
                                       | (SecurityProtocolType)0x300 //Tls11
                                       | (SecurityProtocolType)0xC00; //Tls12

如此即可。

事實上,這個問題正是因為我的客戶端是基於.net 4.0的,而4.0的ServicePointManager.SecurityProtocol預設就不含Tls11和Tls12,所以當服務端改用這兩種安全協議時,自然訪問不了。