Home > Software design >  How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6?
How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6?

Time:12-04

How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6?

I'm stuck on below program.cs:

  builder.Services.AddHttpClient<ITest, Test>(c =>
  {
     c.BaseAddress = new Uri("https://iot.test.com/api");
     c.DefaultRequestHeaders.Accept.Add(new 
     MediaTypeWithQualityHeaderValue("application/json"));
     c.Timeout = TimeSpan.FromMinutes(20);
  }).ConfigureHttpClient((c) =>
     {
      new HttpClientHandler()
      {
         ServerCertificateCustomValidationCallback   = (sender, cert, chain, 
         sslPolicyErrors) =>
         {
             return sslPolicyErrors == SslPolicyErrors.None;
         };
       };
   });

the VS2022 Community IDE keeps saying ServerCertificateCustomValidationCallback doesn't exist in the current context

CodePudding user response:

In order to initialize the ServerCertificateCustomValidationCallback callback like that you need to do some changes:

  • Remove the round brackets after HttpClientHandler, so that you use an object initializer instead of a constructor call.
  • Use = instead of = for assigning the callback handler.
  • Remove the curly brackets around the construction of HttpClientHandler to directly return the newly created object instance without having a method body. (Or add the return keyword to return the object from the method body)
  • Remove some of semicolons

Code:

builder.Services.AddHttpClient<ITest, Test>(c =>
  {
     c.BaseAddress = new Uri("https://iot.test.com/api");
     c.DefaultRequestHeaders.Accept.Add(new 
     MediaTypeWithQualityHeaderValue("application/json"));
     c.Timeout = TimeSpan.FromMinutes(20);
  }).ConfigureHttpClient((c) =>
      new HttpClientHandler
      {
         ServerCertificateCustomValidationCallback = (sender, cert, chain, 
         sslPolicyErrors) =>
         {
             return sslPolicyErrors == SslPolicyErrors.None;
         }
       }
   );
  • Related