詳解.NET Core 使用HttpClient SSL請求出錯的解決辦法
問題
使用 HTTP Client 請求 HTTPS 的 API 時出現(xiàn) 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); } }
原因
因為在發(fā)出 HTTPS 請求的時候,HttpClient 都會檢查 SSL 證書是否合法。如果不合法的話,就會導致拋出異常信息,而對方給出的證書是自簽發(fā)的測試接口的證書,所以不是一個合法的 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"); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- .NET Core中使用HttpClient的正確姿勢
- .Net Core下HTTP請求IHttpClientFactory示例詳解
- .NET Core中HttpClient的正確打開方式
- .NET Core 2.1中HttpClientFactory的最佳實踐記錄
- ASP.NET Core針對一個使用HttpClient對象的類編寫單元測試詳解
- .NET Core使用HttpClient進行表單提交時遇到的問題
- Asp.Net Core2.1前后使用HttpClient的兩種方式
- .net Core 使用IHttpClientFactory請求實現(xiàn)
- .NET CORE HttpClient的使用方法
相關文章
詳解.Net Core 權限驗證與授權(AuthorizeFilter、ActionFilterAttribute)
這篇文章主要介紹了.Net Core 權限驗證與授權(AuthorizeFilter、ActionFilterAttribute),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04解決ASP.NET回傳后div滾動條位置復位的問題(利用隱藏控件原理)
這篇文章主要介紹了解決ASP.NET回傳后div滾動條位置復位的問題,中心思想是用一個隱藏控件保存當前scorll值?;貍骰貋砗蟾鶕?jù)scrollTop的值,然后在Page_Load中重新設置scrollTop2014-01-01Automation服務器不能創(chuàng)建對象的多種解決辦法
這篇文章主要介紹了Automation服務器不能創(chuàng)建對象的多種解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-01-01