gpt4 book ai didi

c# - 在没有显式 ServicePointManager.SecurityProtocol 调用的情况下,.NET 4.7 中未协商 TLS 1.2

转载 作者:IT王子 更新时间:2023-10-29 04:21:44 24 4
gpt4 key购买 nike

我需要升级 .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;
}
}

最佳答案

我在针对 4.7.2 的旧版应用程序中遇到了同样的问题(仅限 Windows 10 和 SSL3/TLS……不是系统默认值)。我的问题是,在多年来的升级过程中,我们从未将 targetFramework 添加到 system.web > httpRuntime 元素(注意:它确实存在于 system.web > compilation 元素上)。在采取更大的步骤之前,确保您的 system.web 看起来像下面这样:

<system.web>
<compilation targetFramework="4.7.2"></compilation>
<httpRuntime targetFramework="4.7.2" />
</system.web>

在上面的示例中,将 4.7.2 替换为您当前使用的 >= 4.7 的框架版本。

关于c# - 在没有显式 ServicePointManager.SecurityProtocol 调用的情况下,.NET 4.7 中未协商 TLS 1.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44751179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com