我需要升级一个.NET应用程序以支持调用仅支持TLS 1.2的网站上的API。从我所读的内容来看,如果该应用程序针对4.6或更高版本,则默认使用TLS 1.2。
为了测试,我创建了一个Windows Forms应用程序,目标是4.7。不幸的是,当我没有明确设置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的Windows 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;
}
}