調用Https WebService是報“基礎連接已經關閉: 未能爲 SSL/TLS 安全通道建立信任關係”的解決過程

今天在通過C#訪問Webservice時遇到一個問題,首先通過對方提供的wsdl生成了調用代理類,在測試能否正常訪問時,訪問正式環境https://api.xxx.xx,一切正常,當訪問測試環境是https://apitest.xxx.xxx,總是報“基礎連接已經關閉: 未能爲 SSL/TLS 安全通道建立信任關係”  InnerException信息爲:根據驗證過程,遠程證書無效。

 

在網上找到解決方法:

http://social.microsoft.com/Forums/zh-CN/wcfzhchs/thread/1591a00d-d431-4ad8-bbd5-34950c39d563

 

依照上面的描述操作,問題解決,以作紀念

 

分以下三步:

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;//驗證服務器證書回調自動驗證

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章