程序會間歇性訪問某個https接口,一直用的好好的,今天突然報錯了,異常就發生在訪問接口的地方,曰“請求被中止,未能創建 SSL/TLS 安全通道。”,另外有台電腦也有跑該程序,也是同樣的報錯,看來是接口方改動過什么了。
搜索一番,原因應該是,接口方變更了安全協議,而客戶端並未啟用該協議。解決辦法自然就是:讓客戶端啟用該協議。具體就是在發起網絡請求之前確保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