详解.NET Core 使用HttpClient SSL请求出错的解决办法
网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要介绍了.NET Core 使用HttpClient SSL请求出错的解决办法,长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧
问题
使用 HTTP Client 请求 HTTPS 的 API 时出现 The certificate cannot be verified up to a trusted certification authority
异常,并且证书已经传入。
狼蚁网站SEO优化就是问题代码:
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"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程