首页 > 解决方案 > 无法发送 HTTP 请求,因为请求被中止。“无法创建 SSL/TLS 安全通道”

问题描述

我目前正在开发一个使用 Invoice Ninja 的 API 来检查付款/发票信息的 C# Web 应用程序。我已经设法使用 HttpClient 在我的本地计算机上运行它,但是每当它部署到部署服务器(Windows Azure VM)时,我都会收到以下错误:

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

启用和未启用 SSL 的两个站点的错误都是相同的(开发站点没有,而实时站点有)。

我尝试使用以下解决方案:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;在创建 HttpClient 之前添加。

使用

WebRequestHandler handler = new WebRequestHandler(); 
handler.ServerCertificateCustomValidationCallback += (sender, certificate, chain, errors) => true;
using (HttpClient client = new HttpClient(handler)) {
     //Code goes here
}

手动将证书添加到WebRequestHandlerfrom

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection = store.Certificates;

我在应用程序中执行的所有其他 HTTP 调用(Twilio、Authy、SendGrid)都按预期工作,但调用 Invoice Ninja 让我很困惑。

我不完全确定从这里去哪里,任何帮助将不胜感激。

编辑:我制作了一个简单的控制台应用程序来检查是否是 IIS 弄乱了 Http 调用,但不幸的是,同样的事情仍然发生。我仍然收到“请求被中止:无法创建 SSL/TLS 安全通道”。错误。

这可能是某种服务器配置问题吗?

编辑 2:我尝试在不同的 VM 上运行控制台测试应用程序,它在那里正常运行。我更不确定从这里去哪里。

这是我尝试过的代码,以防万一。

public static async Task<string> CallInvoiceNinja()
{
    var resultString = string.Empty;

    try
    {
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

        WebRequestHandler handler = new WebRequestHandler();
        using (HttpClient client = new HttpClient(handler))
        {
             client.BaseAddress = new Uri("https://app.invoiceninja.com");
             client.DefaultRequestHeaders.Add("X-Ninja-Token", "[TOKEN]");

             var result = await client.GetAsync("/api/v1/payments");
             resultString = await result.Content.ReadAsStringAsync();
        }
    }
    catch(Exception ex)
    {
       resultString = ex.Message;
       if(ex.InnerException != null)
       {
            resultString += "\n" + ex.InnerException.Message;
       }
     }

     return resultString;
}

标签: c#sslssl-certificatedotnet-httpclientazure-virtual-machine

解决方案


看起来我以错误的方式看待问题。

我做了更多的探索,并试图在服务器上的 IE 中打开他们的 API 的 Swagger 文档,并发现这是由于我们的服务器没有 Invoice Ninja 所需的必要密码套件引起的,因为我们的服务器显然正在使用密码套件的自定义列表。

我添加了 API 使用的密码套件,并重新启动了 VM。我仍然需要ServicePointManager.SecurityProtocol |=SecurityProtocolType.Tls12;网络应用程序的线路,但除此之外,问题实际上已解决。


推荐阅读