3

I'm trying to ignore ssl policy to do a request with HttpClient but ServerCertificateValidationCallback is never called. What is the correct place to invoke ServerCertificateValidationCallback in ASP.NET Core App? I put it before HttpClient using.

Note: This class is in net462 Class Library.

Code:

 System.Net.ServicePointManager.ServerCertificateValidationCallback += 
 delegate (object sender,      
 System.Security.Cryptography.X509Certificates.X509Certificate certificate,
 System.Security.Cryptography.X509Certificates.X509Chain chain,
 System.Net.Security.SslPolicyErrors sslPolicyErrors)
 {
     return true; 
 };

 using (var client = new HttpClient())
 {
    client.BaseAddress = new Uri("https://myapi");
    ...

    var result = client.PostAsync(method, httpContent).Result;
    ...
 }
Carlos
  • 664
  • 1
  • 7
  • 12

2 Answers2

2

Consider trying it like this

//Handle TLS protocols
System.Net.ServicePointManager.SecurityProtocol =
    System.Net.SecurityProtocolType.Tls
    | System.Net.SecurityProtocolType.Tls11
    | System.Net.SecurityProtocolType.Tls12;

var client = new HttpClient();
client.BaseAddress = new Uri("https://myapi");
//...

var result = await client.PostAsync(method, httpContent);
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • The Security protocol works in one of my projects. I can see in Fiddler that the HTTPS protocol send the security headers corretly (Acess-Control-AllowHeaders: Content-Type, api_key, Autohorization). However, in other project with the same request the Headers are not present, and it is sending HTTP. I'm looking for a answer for this behavior. If you have any idea this will be welcome. I will be glad to share when I overcome this bug. Thanks! – Carlos Jul 06 '17 at 18:10
0

Try putting the callback initialization code earlier - before web controls are displayed or the main function.

Credit goes to this answer :https://stackoverflow.com/a/5043083/1709981

tony
  • 1,274
  • 1
  • 11
  • 27