自簽署憑證

May 16, 2023

開發的程式若需連接到使用自簽署憑證的 API,可以用 Postman 檢查,並在 C# 內調整連線方式。

關於自簽署憑證

使用 Postman 測試

  • 在 Postman 的設定中,於 General 頁籤裡將 SSL Certificate Verification 選項關閉,即可正常連線。

SSL Certificate Verification

在 C# 中如何處理自簽署憑證

其他可能的做法

Untrusted Root 問題

如果在連線到伺服器時,發生以下的錯誤:

AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: NotValidTime, UntrustedRoot

這是自簽署憑證的問題,可以跳過驗證:

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
    (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

var client = new HttpClient(handler);