使用HttpClient访问http站点,正常。
使用HttpClient访问带有合法证书的https站点,正常。
但,使用HttpClient访问“不合法证书”的https站点,如直接使用IP地址访问,则出现异常。
代码如下
var aa = new HttpClient();
var a1 = aa.GetAsync("http://x.x.x.x/health");
var a2 = a1.Result;
异常内容:
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
处理办法:
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;
这样,就不再报异常了。