首页 > 解决方案 > 如何使用 .NET HttpClient 获取服务器证书无效的原因?

问题描述

Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure

因此,关于此异常有很多答案,但其中大多数似乎都可以通过说“不要使用无效证书”来解决。

很公平,但我知道证书被视为无效的原因可能有很多(参见:https ://badssl.com/ ),但提到的异常只是告诉我们“它无效”,我没有找到该异常的任何属性以及更多详细信息。

所以代码可能看起来像这样。我如何弄清楚为什么证书被认为是无效的?甚至可以使用 HttpClient 还是我必须以另一种方式检查证书?

var client = new HttpClient();
try
{
    using (var msg = new HttpRequestMessage(HttpMethod.Get, "https://expired.badssl.com/"))
    {
        using (var response = await client.SendAsync(msg))
        {
            // do stuff with the response
        }
    }
}
catch (AuthenticationException ex)
{
    // why is the certificate invalid?
}

标签: c#.nethttps

解决方案


这里写得很好: https

://ardalis.com/automatically-detect-expiring-https-ssl-certificates/ 基本上你发出一个 Web 请求并处理服务器证书验证回调,在那里你可以找出 SSL 错误的原因


推荐阅读