gpt4 book ai didi

c# - 使用 HttpClient (.NET) 时出现 SSL 策略错误

转载 作者:行者123 更新时间:2023-12-04 22:36:27 27 4
gpt4 key购买 nike

我正在尝试使用具有自签名证书的本地 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com