zoukankan      html  css  js  c++  java
  • .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
    ootTrust.cer","11111111"),
    				new X509Certificate2(@"E:certmiddleTrust.cer","11111111"),
    				new X509Certificate2(@"E:certwskey.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
    ootTrust.cer","11111111"),
    				new X509Certificate2(@"E:certmiddleTrust.cer","11111111"),
    				new X509Certificate2(@"E:certwskey.pfx","ws654321")
    			}
    		};
    		
    		var webRequest = new HttpClient(handler);
    		var result = webRequest.GetStringAsync(url).GetAwaiter().GetResult();
    		Console.WriteLine("xx");
    	}
    }
    
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/myzony/p/10482113.html
Copyright © 2011-2022 走看看