用httpwebrequest訪問一個SSL類型的地址 https://xxxx 時,報錯 “未能為 SSL/TLS 安全通道建立信任關係(Could not establish trust relationship for the SSL/TLS secure channel)”
查了下MSDN,找到瞭解決方法,SSL網站,串連時需要提供認證,對於非必須提供用戶端認證的情況,只要返回一個安全確認即可。但是此方法的實現,在.NET 1.1 和 .NET 2.0 下是不同的,下面寫出2個framework版本下的實現方法:
使用的命名空間:
using System.Net;using System.Net.Security;using System.Security.Authentication;using System.Security.Cryptography.X509Certificates;
.Net 2.0
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors){ //直接確認,否則打不開 return true;} private void button1_Click(object sender, EventArgs e){ ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri("https://zu14.cn/")); req.Method = "GET"; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); //...正常使用了,和訪問普通的 http:// 地址一樣了
.Net 1.1
internal class AcceptAllCertificatePolicy : ICertificatePolicy{ public AcceptAllCertificatePolicy() { } public bool CheckValidationResult(ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest wRequest, int certProb) { //直接確認 return true; }} private void button1_Click(object sender, EventArgs e){ ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri("https://zu14.cn/")); req.Method = "GET"; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); //...正常使用了,和訪問普通的 http:// 地址一樣了