c# - ASP.Net MVC 应用程序默认为 TLS 1.0
问题描述
我们有一个 ASP.Net MVC 应用程序,它使用服务器到服务器的通信来检索一些信息。
当我们在 AWS 云中运行安装时,请求失败,因为默认情况下,WebRequest 使用我们在环境中禁用的 TLS 1.0。在另一个项目中使用相同的代码默认为 TLS 1.2。此外,在ServicePointManager中对协议进行硬编码可以解决此问题。
有没有人遇到过类似的问题和根本原因?我想在不对协议进行硬编码的情况下解决这个问题,因为它不是面向未来的。
解决方案
我遇到了类似的问题,最后只是将其设置为配置设置:
//read setting as comma-separated string from wherever you want to store settings
//e.g. "SSL3, TLS, TLS11, TLS12"
string tlsSetting = GetSetting('tlsSettings')
//by default, support whatever mix of protocols you want..
var tlsProtocols = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
if (!string.IsNullOrEmpty(tlsSetting))
{
//we have an explicit setting, So initially set no protocols whatsoever.
SecurityProtocolType selOpts = (SecurityProtocolType)0;
//separate the comma-separated list of protocols in the setting.
var settings = tlsSetting.Split(new[] { ',' });
//iterate over the list, and see if any parse directly into the available
//SecurityProtocolType enum values.
foreach (var s in settings)
{
if (Enum.TryParse<SecurityProtocolType>(s.Trim(), true, out var tmpEnum))
{
//It seems we want this protocol. Add it to the flags enum setting
// (bitwise or)
selOpts = selOpts | tmpEnum;
}
}
//if we've allowed any protocols, override our default set earlier.
if ((int)selOpts != 0)
{
tlsProtocols = selOpts;
}
}
//now set ServicePointManager directly to use our protocols:
ServicePointManager.SecurityProtocol = tlsProtocols;
这样,您可以启用/禁用特定协议,如果在枚举定义中添加或删除任何值,您甚至不需要重新访问代码。
显然,映射到枚举的以逗号分隔的事物列表作为设置有点不友好,但是您可以设置某种映射或其他任何东西,当然,如果您愿意……它很好地满足了我们的需求。
推荐阅读
- azure-web-app-service - Azure Webapp(Windows):对外部链接的 URL 重写返回错误
- bash - 在 bash 中有效获取命令输出的一致语法?
- android - 如何在 Android Studio 中通过 logcat 或终端查看 Google Analytics 测量协议(调试)
- django - django如何将上传到数据库的文件的链接和实际文件的链接保存在django的特定文件夹中
- function - Kotlin - 将 sortBy 参数作为函数参数传递
- java - 我如何使用 volley 从服务器发送和验证参数?
- python - 按元素对列表组合求和
- reactjs - 在 JSX 中定义变量
- circleci - 带有 Circle CI 覆盖源的 Codecov
- reactjs - 登录前后渲染组件