如何忽略SSL策略来执行HTTPClient请求?

时间:2017-07-05 14:52:04

标签: c# asp.net ssl-certificate

我试图忽略ssl策略来使用HttpClient执行请求,但从不调用ServerCertificateValidationCallback。在ASP.NET Core App中调用ServerCertificateValidationCallback的正确位置是什么?我把它放在HttpClient之前使用。

注意:此类位于net462类库中。

代码:

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

2 个答案:

答案 0 :(得分:1)

考虑像这样尝试

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

答案 1 :(得分:0)

在显示Web控件或主要功能之前,请先尝试放回回调初始化代码。

归功于这个答案:https://stackoverflow.com/a/5043083/1709981