由于请求中止,因此无法发送HTTP请求。 “无法创建SSL / TLS安全通道”

时间:2019-08-19 08:48:32

标签: c# ssl ssl-certificate dotnet-httpclient azure-virtual-machine

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

  

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

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

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

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

使用

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

手动将证书添加到WebRequestHandler
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上运行控制台测试应用程序,并且该应用程序在该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;
}

1 个答案:

答案 0 :(得分:0)

看来我是用错误的方式看问题。

我做了一些进一步的尝试,并尝试在服务器上的IE中打开其API的Swagger文档,结果发现这是由于我们的服务器没有Invoice Ninja所需的必要密码套件引起的,因为我们的服务器显然是使用自定义的密码套件列表。

我添加了API使用的密码套件,然后重新启动了VM。我仍然需要用于Web应用程序的ServicePointManager.SecurityProtocol |=SecurityProtocolType.Tls12;行,但是除此之外,该问题实际上已经解决。