.NET Core 使用 HttpClient SSL 请求出错的解决办法
生活随笔
收集整理的這篇文章主要介紹了
.NET Core 使用 HttpClient SSL 请求出错的解决办法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問題
使用 HTTP Client 請(qǐng)求 HTTPS 的 API 時(shí)出現(xiàn)?The certificate cannot be verified up to a trusted certification authority?異常,并且證書已經(jīng)傳入。
下面就是問題代碼:
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);
}
}
原因
因?yàn)樵诎l(fā)出 HTTPS 請(qǐng)求的時(shí)候,HttpClient?都會(huì)檢查 SSL 證書是否合法。如果不合法的話,就會(huì)導(dǎo)致拋出異常信息,而對(duì)方給出的證書是自簽發(fā)的測(cè)試接口的證書,所以不是一個(gè)合法的 SSL 證書。
解決
在?HttpClientHandler?當(dāng)中會(huì)有一個(gè)?ServerCertificateCustomValidationCallback?事件,該事件用于判定證書驗(yàn)證是否通過。我們可以掛接該事件,然后邏輯編寫為直接返回?true?結(jié)果,這樣就會(huì)忽略掉證書異常的情況。
最新的代碼如下:
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");
}
}
原文地址:https://www.cnblogs.com/myzony/p/10482113.html
.NET社區(qū)新聞,深度好文,歡迎訪問公眾號(hào)文章匯總 http://www.csharpkit.com
總結(jié)
以上是生活随笔為你收集整理的.NET Core 使用 HttpClient SSL 请求出错的解决办法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Core中实现单体程序的
- 下一篇: 【.NET Core项目实战-统一认证平