The Will Will Web

記載著 Will 在網路世界的學習心得與技術分享

Troubleshooting: 根據驗證程序,遠端憑證是無效的。

我想一定有人遇過這個問題,就是當使用 WebClient 或 WebRequest 類別抓取 HTTPS/SSL 的網頁時,出現以下錯誤訊息:

那是因為 .Net 針對安全的網路連線必須要有正確可受信任的憑證才可以連接!

如果你原本的程式長這樣:

[code:c#]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebClient client = new WebClient();

        Stream data = client.OpenRead("https://www.securedomain.com.tw/index.aspx");
        StreamReader reader = new StreamReader(data);

        string s = reader.ReadToEnd();

        data.Close();
        reader.Close();

        Response.Write(s);
    }
}
[/code]

你只要改成這樣就可以忽略憑證檢查的步驟了!

[code:c#]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public partial class _Default : System.Web.UI.Page
{
    // 設定 HTTPS 連線時,不要理會憑證的有效性問題
    public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // 設定 HTTPS 連線時,不要理會憑證的有效性問題
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

        WebClient client = new WebClient();

        Stream data = client.OpenRead("https://www.securedomain.com.tw/index.aspx");
        StreamReader reader = new StreamReader(data);

        string s = reader.ReadToEnd();

        data.Close();
        reader.Close();

        Response.Write(s);
    }
}
[/code]

注意事項

‧記得要載入兩個命名空間:

[code:c#]
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
[/code]

相關連結 (於 2010/8/7 補充)