我正在尝试使用具有自签名证书的本地 Web 服务器上的 REST API。在运行时,应用程序抛出错误
AuthenticationException: The remote certificate is invalid according to the validation procedure.
我已尝试此答案中的修复:https://stackoverflow.com/a/1386568/8980983但错误仍然存在。代码如下:
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Clear();
ServicePointManager.ServerCertificateValidationCallback = delegate (
object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
var loginPage = httpClient.GetAsync("https://<local IP address>/loginpage.html").GetAwaiter().GetResult();
//do stuff with response...
}
我可以采取哪些措施来有效忽略 SSL 策略错误?
最佳答案
想通了。结果 HttpClient 类不使用 ServicePointManager.ServerCertificateValidationCallback
方法。解决办法如下:
static void Main(string[] args)
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.Clear();
var loginPage = httpClient.GetAsync("https://<local IP address>/loginpage.html").GetAwaiter().GetResult();
}
关于c# - 使用 HttpClient (.NET) 时出现 SSL 策略错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61394174/