詳解.NET Core 使用HttpClient SSL請求出錯的解決辦法

這篇文章主要介紹了.NET Core 使用HttpClient SSL請求出錯的解決辦法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

問題

使用 HTTP Client 請求 HTTPS 的 API 時出現 The certificate cannot be verified up to a trusted certification authority 異常,並且證書已經傳入。

下面就是問題代碼:

public class Program
{
 public static void Main(string[] args)
 {
  var url = @"https://xxx.xxx.xxx.xxx:xxxx/xxx-web/services/xxxx?wsdl";

  var handler = new HttpClientHandler
  {
   ClientCertificateOptions = ClientCertificateOption.Manual,
   ClientCertificates =
   {
    new X509Certificate2(@"E:\cert\rootTrust.cer","11111111"),
    new X509Certificate2(@"E:\cert\middleTrust.cer","11111111"),
    new X509Certificate2(@"E:\cert\wskey.pfx","ws654321")
   }
  };
  
  var webRequest = new HttpClient(handler);
  var result = webRequest.GetStringAsync(url).GetAwaiter().GetResult();
  Console.WriteLine(result);
 }
}

原因

因爲在發出 HTTPS 請求的時候,HttpClient 都會檢查 SSL 證書是否合法。如果不合法的話,就會導致拋出異常信息,而對方給出的證書是自簽發的測試接口的證書,所以不是一個合法的 SSL 證書。

解決

HttpClientHandler 當中會有一個 ServerCertificateCustomValidationCallback 事件,該事件用於判定證書驗證是否通過。我們可以掛接該事件,然後邏輯編寫爲直接返回 true 結果,這樣就會忽略掉證書異常的情況。

最新的代碼如下:

public class Program
{
 public static void Main(string[] args)
 {
  var url = @"https://xxx.xxx.xxx.xxx:xxxx/xxx-web/services/xxxx?wsdl";

  var handler = new HttpClientHandler
  {
   ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true, 
   ClientCertificateOptions = ClientCertificateOption.Manual,
   ClientCertificates =
   {
    new X509Certificate2(@"E:\cert\rootTrust.cer","11111111"),
    new X509Certificate2(@"E:\cert\middleTrust.cer","11111111"),
    new X509Certificate2(@"E:\cert\wskey.pfx","ws654321")
   }
  };
  
  var webRequest = new HttpClient(handler);
  var result = webRequest.GetStringAsync(url).GetAwaiter().GetResult();
  Console.WriteLine("xx");
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

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