[Original] Error handling when HttpClient accesses "unreliable" Https

Use HttpClient to access the http site, it is normal.
Use HttpClient to access https sites with legal certificates, normal.
However, if you use HttpClient to access the "invalid certificate" https site, if you directly use the IP address to access, an exception will occur.

code show as below

var aa = new HttpClient();
var a1 = aa.GetAsync("http://x.x.x.x/health");
var a2 = a1.Result;

Exception content:

System.AggregateException:“One or more errors occurred. (The SSL connection could not be established, see inner exception.)”

AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors

Solution:

 HttpClientHandler clientHandler = new HttpClientHandler();
 clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => {
    
     return true; };
 clientHandler.SslProtocols = SslProtocols.None;

 var aa = new HttpClient(clientHandler);
 var a1 = aa.GetAsync("https://x.x.x.x/health");
 var a2 = a1.Result;

In this way, no exception will be reported.

Guess you like

Origin blog.csdn.net/u013667796/article/details/130442415