C# HttpClient:无法创建SSL/TLS安全通道

4

我想向"https://etebarkala.com"发送一个简单的请求。

  1. 尝试了从.net版本4.5到4.8,但没有成功
  2. 这个网站可以用浏览器很容易地打开
  3. 没有任何SSL验证错误或警告

结果:请求被中止:无法创建SSL/TLS安全信道。

var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://etebarkala.com"));
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0");
request.Headers.Add("Upgrade-Insecure-Requests", "1");
request.Headers.Add("Connection", "keep-alive");


using (HttpClientHandler handler = new HttpClientHandler())
{
    handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;//| SslProtocols.Ssl3;//| SslProtocols.Ssl3;
    handler.ServerCertificateCustomValidationCallback = (snder, cert, chain, error) => { return true; };

    ServicePointManager.ServerCertificateValidationCallback = (snder, certificate, chain, errors) => { return true; };

    ServicePointManager.DefaultConnectionLimit = 9999;
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault;

    using (HttpClient client = new HttpClient(handler))
    {
        try
        {
                HttpResponseMessage res = client.SendAsync(request).Result;
                textBox1.Text = res.Content.ReadAsStringAsync().Result;
        }
        catch (Exception e)
        {
                string Result = e.Message;
                textBox1.Text = "Error:" + Result
            + Environment.NewLine + (e.InnerException != null ? e.InnerException.Message : "")
            + Environment.NewLine + (e.InnerException != null && e.InnerException.InnerException != null ? e.InnerException.InnerException.Message : "");

        }
    }
}

与您的问题无关,但请注意在使用“异步”方法时要小心。在任务上调用.Result几乎永远不是您想要做的事情;它很可能会导致您的应用程序死锁或产生其他不希望的行为。相反,您的方法应该是“async”,并且应该“await”该任务。例如:await client.SendAsync(request); - Daniel Mann
@DanielMann 谢谢您的注意,我明白了,这是测试代码。 - Masoud Chegeni
2个回答

1
在我的情况下,访问本地机器存储中的证书的权限是问题所在。我通过证书指纹从机器存储中读取HttpClient的证书,但一旦调用SendAsync方法,就会出现“请求被中止:无法创建SSL/TLS安全通道。”异常。

请以管理员身份运行certlm.msc,右键单击目标证书,选择所有任务 -> 管理私钥,然后为您的进程正在访问的存储下的用户添加权限。如果是IIS,则可能是NETWORK SERVICE。

-1
加入以下代码即可,轻松解决问题:
ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

仔细审查问题。那些行代码已经存在。 - Daniel Mann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接