【发布时间】:2017-11-28 18:57:01
【问题描述】:
我需要升级 .NET 应用程序以支持对仅支持 TLS 1.2 的网站上的 API 的调用。根据我的阅读,如果应用程序的目标是 4.6 或更高版本,那么默认情况下它将使用 TLS 1.2。
为了测试,我创建了一个面向 4.7 的 Windows 窗体应用程序。不幸的是,当我没有明确设置 ServicePointManager.SecurityProtocol 时它会出错。代码如下:
HttpClient _client = new HttpClient();
var msg = new StringBuilder();
// If I uncomment the next line it works, but fails even with 4.7
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://sandbox.authorize.net");
httpWebRequest.KeepAlive = false;
try
{
var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
msg.AppendLine("The HTTP request Headers for the first request are: ");
foreach (var header in httpWebRequest.Headers)
{
msg.AppendLine(header.ToString());
}
ResponseTextBox.Text = msg.ToString();
}
catch (Exception exception)
{
ResponseTextBox.Text = exception.Message;
if (exception.InnerException != null)
{
ResponseTextBox.Text += Environment.NewLine + @" ->" + exception.InnerException.Message;
if (exception.InnerException.InnerException != null)
{
ResponseTextBox.Text += Environment.NewLine + @" ->" + exception.InnerException.InnerException.Message;
}
}
}
如果您取消注释以下行:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
它有效。这不是一个好的解决方案,因为它对要使用的 TLS 版本进行硬编码,因此将来不会使用 TLS 1.3。
如果没有这条线,我还需要做什么才能让它工作。我正在安装 4.7 的 Window 10 机器上进行测试。
更新
我尝试使用 HttpClient 进行测试并得到相同的结果,我必须明确设置 SecurityProtocol。
代码:
var msg = new StringBuilder();
// Need to uncomment code below for TLS 1.2 to be used
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
var response = await _client.GetAsync(@"https://sandbox.authorize.net");
msg.AppendLine("response.IsSuccessStatusCode : " + response.IsSuccessStatusCode);
msg.AppendLine(await response.Content.ReadAsStringAsync());
textBox.Text = msg.ToString();
}
catch (Exception exception)
{
textBox.Text = exception.Message;
if (exception.InnerException != null)
{
textBox.Text += Environment.NewLine + @" ->" + exception.InnerException.Message;
}
}
【问题讨论】:
-
如果您愿意,您可以将 tls 版本组合在一起以支持它们。但是为了避免这种使用 HttpClient 的需要(如果你可以让你的代码异步而没有任何阻塞调用)
-
我不想定义安全协议,因为当 TLS 1.3 等新协议可用时,它不会被使用,因为它不在列表中。我将用 HttpClient 重写我的测试,HttpClient 与 HttpWebResponse 使用的默认安全协议有区别吗?
-
不要相信我的话,但我假设 HttpClient 将支持协商可用于 CLR 版本的最高协议。因此,您的下一个砖墙将需要 CLR 升级而不是代码升级。这可能是一个可怕的想法,但我想知道如果你只打开所有位会发生什么:
SecurityProtocolType s = (SecurityProtocolType)2147483647; -
有趣。查看有关 v4.7 的此发行说明github.com/Microsoft/dotnet/blob/master/releases/net47/…
-
这很有趣。我试图将其设置为“SystemDefault”,但失败了。假设它是默认值,那么 TLS 1.2 应该是 Win10 OS 上使用的值。
标签: c# .net winforms httpwebrequest tls1.2