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

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

![](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/3ac4dab1448cdb2ad698-Screenshot_-_2007-11-01______02_27_30.png)

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

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

```csharp
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);
    }
}
```

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

```csharp
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);
    }
}
```

**注意事項**

> ‧記得要載入兩個命名空間：
> 
> ```csharp
> using System.Net.Security;
> using System.Security.Cryptography.X509Certificates;
> ```

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

-   [Send a HTTPS POST request with C#](http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/)
-   [Tip/Trick: Enabling SSL on IIS 7.0 Using Self-Signed Certificates](https://weblogs.asp.net/scottgu/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates)
-   [C#: How to accept an invalid SSL certificate programmatically](https://web.archive.org/web/20200214215015/http://blog.jameshiggs.com:80/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically)
