C# 請求被中止: 未能創建 SSL/TLS 安全通道。 設置SecurityProtocol無效
今天為了獲取一張圖片,用了一段程式碼:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((a, b, c, d) => true); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.Expect100Continue = false; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(imgUrl); req.AllowAutoRedirect = true; req.KeepAlive = true; req.Method = "GET"; WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream();
裡面添加了ServicePointManager.SecurityProtocol,但是一直還是報錯:”請求被中止: 未能創建 SSL/TLS 安全通道。”
然後網上參考了一下://blog.csdn.net/yunwu009/article/details/80768860
下載了證書,加到程式碼中:
string filePath =".\\cer\\specifier.cer"; X509Certificate2 cert = new X509Certificate2(filePath); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(imgUrl); //將證書添加客戶端證書集合 req.ClientCertificates.Add(cert);
但是仍然無效。
感覺非常奇怪,然後通過DevTools看了一下圖片網址的協議版本:
發現版本已經到了TLS 1.3了,因為我本地的版本是.net framework 4.7 ,還沒有支援Tls1.3版本,於是修改了ServicePointManager.SecurityProtocol:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | (SecurityProtocolType)12288;
結果換了新的報錯:不支援請求的安全協議。
網上說只有最新的.net 5裡面才支援了Tls1.3版本,那.net framework系列就沒有解決辦法了嗎?
該怎麼解決?求助各位大神!!!