gpt4 book ai didi

c# - ServicePointManager.SecurityProtocol 不是 SecurityProtocolType.SystemDefault

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:10 26 4
gpt4 key购买 nike

我在 Windows 10 1903 上,我的 IE 和 Chrome 无需任何特殊设置即可访问 Tls 1.2 网站。但是当我尝试使用我的 .net 4.7.2 应用程序访问只允许 Tls 1.2 连接的 Web API 时,我的连接被服务器终止了。

我必须在我的代码中添加 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; 以允许我的应用程序正确连接到该端点。

但经过一些研究,我发现来自 this记录 .Net 4.7 及更高版本的 ServicePointManager.SecurityProtocol 的默认值应为 SecurityProtocolType.SystemDefault 并根据 this记录默认情况下启用 Tls 1.2 协议(protocol)。

所以我跟踪我的代码,发现我系统上 ServicePointManager.SecurityProtocol 的默认值是 System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls。更疯狂的是,当我将协议(protocol)设置为 SecurityProtocolType.SystemDefault 时,我得到了这个错误:

System.Net.Http.HttpRequestException : An error occurred while sending the request.
---- System.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive.
-------- System.ArgumentException : The specified value is not valid in the 'SslProtocolType' enumeration.
Parameter name: sslProtocolType

我检查了我的系统 registry和 IE 设置,并且没有任何内容会覆盖或禁用 Tls 1.2。

所以我很困惑,想知道是不是我的系统或我的代码有问题。

最佳答案

如果您正在运行的应用程序目标早于 4.6 的 .NET 框架(即使您实际上是在较新的 .NET FX 上运行它),您将收到此错误。您可以通过检查 AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName 的值来检查这一点。

具体来说,这将在 SystemDefaultTlsVersions 的情况下被抛出注册表值未设置为 1: https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,164

AppContext switches也不会帮助你,因为它们只对从 4.6 开始的框架版本生效。假设您不能更改目标 .NET 版本 ( example ) 并且您不想强制您的用户更改他们的注册表设置,我推荐这样的代码:

if (ServicePointManager.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

更多信息: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls

关于c# - ServicePointManager.SecurityProtocol 不是 SecurityProtocolType.SystemDefault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57879579/

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