呼叫Https WebService是報“基礎連線已經關閉: 未能為 SSL/TLS 安全通道建立信任關係”的解決過程
今天在通過C#訪問Webservice時遇到一個問題,首先通過對方提供的wsdl生成了呼叫代理類,在測試能否正常訪問時,訪問正式環境https://api.xxx.xx,一切正常,當訪問測試環境是https://apitest.xxx.xxx,總是報“基礎連線已經關閉: 未能為 SSL/TLS 安全通道建立信任關係” InnerException資訊為:根據驗證過程,遠端證書無效。
在網上找到解決方法:
依照上面的描述操作,問題解決,以作紀念
分以下三步:
1. 新增引用
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
2. 在生成的代理類中新增RemoteCertificateValidate函式
private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error){
// trust any certificate!!!
System.Console.WriteLine("Warning, trust any certificate");
//為了通過證書驗證,總是返回true
return true;
}
3. 在生產的代理類的建構函式中新增
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;//驗證伺服器證書回撥自動驗證