无法发送 HTTP 请求,因为请求已中止。 "Could not create SSL/TLS secure channel"



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

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

对于启用和未启用 SSL 的站点,错误是相同的(开发站点没有 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 上运行控制台测试应用,它在那里正常运行。我更不确定该何去何从。

这是我尝试过的代码,以防万一它有帮助。

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;
}

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

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

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

最新更新