NET Core Solution to Error in Using HttpClient SSL Request

  • 2021-11-02 00:37:24
  • OfStack

Problem

Occurs when API of HTTPS is requested using HTTP Client The certificate cannot be verified up to a trusted certification authority Exception, and the certificate has been passed in.

Here's the problem code:


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);
 }
}

Cause

Because HttpClient will check whether the SSL certificate is legal when issuing HTTPS request. If it is illegal, it will cause an exception message to be thrown, and the certificate given by the other party is a self-issued test interface certificate, so it is not a legal SSL certificate.

Solve

In HttpClientHandler There will be one of them ServerCertificateCustomValidationCallback Event, which is used to determine whether the certificate verification passed. We can hook up the event and then write the logic to return directly true As a result, certificate exceptions are ignored.

The latest code is as follows:


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");
 }
}

Related articles: