我有 .netstandard2.0 项目,由两个项目使用。一种是.net core项目,一种是.netframework4.7.1。在 .netframework4.7.1 中引用我的 .Netstandard2.0 项目时,我收到 HttpClientHandler.SslProtocol 的“PlatformNotSupportedException”。我知道 .netframework4.7.1 不支持它。但我想跳过该代码 .netframework4.7.1 并且不在 .netcore 中跳过。我如何在 .netstansard2.0 中处理这个问题。 我无法访问 .netframework4.7.1 和 .net core。我只能访问使用“HttpClientHandler.SslProtocol”的 .netstandard2.0。我可以在 .netframework4.7.1 和 .net core 中做任何事情。我可以在 .netstandard2.0 中做什么? 在 .netcore 中工作正常。
这是我的代码
private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler() {
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,
ServerCertificateCustomValidationCallback = null,
SslProtocols = System.Security.Authentication.SslProtocols.Tls11
})
{
Timeout = TimeSpan.FromSeconds(45)
};
下面的代码是在实现ihttpclientfactory时
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;
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11;
return handler;
});
var serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetRequiredService<IHttpClientFactory>();
});
为了处理 .NET Standard 和 .NET 4.x 之间的差异,您需要能够编译该库以针对这两个平台。为此,首先更改您的库
.csproj
文件以支持多个目标框架:
<PropertyGroup>
<TargetFrameworks>netstandard20;net471</TargetFrameworks>
....
</PropertyGroup>
现在,在您的代码中,您可以使用为您定义的预处理器符号之一来选择如何处理不同的框架。例如:
var handler = new HttpClientHandler();
//snip
#if NETSTANDARD2_0
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls11;
#endif
//snip
#if NET471
// In .NET 4.x we must use the ServicePointManager class
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
#endif