我在C#中有一個下載方法。該方法向要下載的URL發送請求。但是它給一些URL地址提供了錯誤。我遇到問題的最後一個URL是一個exe文件link。發送HttpWebRequest時SSL/TSL安全通道異常
我的方法:
void DownloadProcedure()
{
#region Request-Response
req = WebRequest.Create(url) as HttpWebRequest;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 5;
req.ServicePoint.ConnectionLimit += 2;
req.ServicePoint.Expect100Continue = true;
req.ProtocolVersion = HttpVersion.Version10;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
if (rangeAllowed)
req.AddRange(from, to);
resp = req.GetResponse() as HttpWebResponse;
#endregion
//...bla bla...
}
。在GetResponse()
這行代碼,它拋出無法建立SSL/TSL安全通道。但它並不總是這樣。有時文件被成功下載,有時它會拋出這個異常。我不知道通過它的正確方法是什麼。
那麼如何才能解決這個問題的一個
首先,此行應僅用於調試。 ServicePointManager.ServerCertificateValidationCallback =委託{return true; };請勿將此代碼投入生產。 – granadaCoder
使用此代碼查看有問題的證書。 ServicePointManager.ServerCertificateValidationCallback = 新System.Net.Security.RemoteCertificateValidationCallback(( 發件人, 證書, 鏈, SSL)=> { Console.WriteLine( 「ServerCertificateValidationCallback爲Cert.Subject: '{0}'」, cert.Subject); System.Net.HttpWebRequest HWR =發送者作爲System.Net.HttpWebRequest; 如果(空= HWR) { SecurityShower.ShowHttpWebRequest(HWR); }! SecurityShower。ShowCertAndChain(cert,chain); 返回true; }); – granadaCoder
您可以在此處獲取ShowCertAndChain代碼:https://granadacoder.wordpress.com/2016/11/04/service-bus-and-custom-self-signed-certificates-with-a-high-availabilitymultiple-computing-nodes在農場/ – granadaCoder