我有两个项目使用的.netstandard2.0项目.一个是. net核心项目,一个是. netframework4.7.1.当我在.netframework4.7.1中引用我的.Netstandard2.0项目时,我得到了HttpClient.sslProtocol的"PlatformNotSupportedException".我知道在.netframework4.7.1中不支持它,但我想跳过代码.netframework4.7.1,不要跳过. netcore.我如何在.netstansard2.0中处理这个问题? 我无法访问.netframework4.7.1和. net核心.我只能访问.netstandard2.0,其中"HttpClient.sslProtocol"使用.我可以在.netframework4.7.1和. net core中做任何事情.我可以在.netstandard2.0中做什么? 在. netcore.netcore.com中运行良好.

这是我的密码

    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>();
    });

我们可以使用下面的代码识别框架版本并相应地执行代码吗?

private string getCallingFramework() {

    return RuntimeInformation.FrameworkDescription;
}

推荐答案

为了处理. NET Standard和. NET 4.x之间的差异,您需要能够编译库以针对两个平台.要做到这一点,首先更改库.csproj文件以支持多个目标框架:

<PropertyGroup>
    <TargetFrameworks>netstandard20;net471</TargetFrameworks>
  ....
</PropertyGroup>

现在,在代码中,您可以 Select 如何使用为您定义的预处理器符号来处理不同的框架.例如:

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

Csharp相关问答推荐

Blazor:用参数创建根路径

为什么xslWriter不总是按照xslWriterSet中指定的格式格式化该文档?

如何在Visual Studio中为C# spread操作符设置格式规则?

在多对多关系上不删除实体

应用程序重新启动后,EFCore列表的BSON反序列化错误

MS Graph v5.42.0:在寻呼消息时更改页面大小

Rx.Net窗口内部可观测数据提前完成

Azure函数中实体框架核心的依赖注入

WinForms在Linux上的JetBrains Rider中的应用

如何通过属性初始化器强制初始化继承记录内的属性?

C#按名称从类获取属性值类型<;t>;,我需要反射吗?

为什么Docker中没有转发该端口?

当我将`ConcurentDictionary`转换为`IDictionary`时,出现了奇怪的并发行为

基于C#方法的EF核心过滤查询(缓冲与流)

在同一个捕获中可以有多种类型的异常吗?

Visual Studio,Docker容器-容器调用:连接被拒绝

c#在后台实现类型化数组

我是否应该注销全局异常处理程序

如何在.NET MAUI上在iOS和Mac之间共享代码?(no条件编译和无代码重复)

将文本从剪贴板粘贴到RichTextBox时,新文本不会在RichTextBox ForeColor中着色