如何在.NET Standard 2.0中处理HttpClientHandler.SslProtocol的平台不支持异常
解决方案:针对.NET Framework 4.7.1跳过SslProtocols属性设置
你可以通过RuntimeInformation.FrameworkDescription在运行时判断当前环境,从而针对性地跳过.NET Framework 4.7.1不支持的SslProtocols设置,以下是两种实现方式的修改方案:
1. 直接创建HttpClient的版本
由于原代码是静态只读字段初始化,需要将逻辑移到静态构造函数中,先判断框架再配置Handler:
private static readonly HttpClient _httpClient; static YourClassName() { var handler = new HttpClientHandler { AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate, ServerCertificateCustomValidationCallback = null }; // 仅在非.NET Framework环境下设置SslProtocols if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework")) { handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11; } _httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(45) }; }
2. IHttpClientFactory实现的版本
在配置PrimaryHttpMessageHandler时加入框架判断逻辑:
private static readonly Lazy<IHttpClientFactory> httpClientFactoryLazy = new Lazy<IHttpClientFactory>(() => { var services = new ServiceCollection(); services.AddHttpClient("HttpClientFactory", client => { client.Timeout = TimeSpan.FromSeconds(15); }) .ConfigurePrimaryHttpMessageHandler(() => { var handler = new HttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // 跳过.NET Framework环境下的SslProtocols设置 if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework")) { handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11; } return handler; }); var serviceProvider = services.BuildServiceProvider(); return serviceProvider.GetRequiredService<IHttpClientFactory>(); });
关键说明
RuntimeInformation.FrameworkDescription的返回值在.NET Framework 4.7.1中为.NET Framework 4.7.1,在.NET Core/.NET 5+中为.NET Core X.X或.NET X,通过StartsWith判断足够可靠。- 这种方式是运行时动态判断,完美适配.NET Standard项目被不同框架引用的场景,无需修改任何引用该Standard项目的外部项目。
- 不推荐用条件编译:因为.NET Standard项目编译时不绑定具体目标框架,条件编译无法区分最终运行时的环境,运行时判断才是正确的选择。
内容的提问来源于stack exchange,提问作者Nishad
相关产品推荐
相关产品推荐

