简体   繁体   English

使用来自 NetStandard2.0 库的 HttpContext 请求/响应/会话

[英]Using HttpContext Request/Response/Session from NetStandard2.0 library

Upgrading a very large .NET Framework 4.8 enterprise application consisting of 70+ applications and 200+ base class libraries (C#)升级一个非常大的 .NET 框架 4.8 企业应用程序,包括 70 多个应用程序和 200 多个基础 class 库(C#)

The base class libraries are being converted to.NetStandard 2.0 so they they can be consumed by .NET Framework and .NET Core Applications.基本的 class 库正在转换为.NetStandard 2.0,因此它们可以被 .NET 框架和 .NET 核心应用程序使用。 Migration of each application can then be be done when ready.然后可以在准备好时完成每个应用程序的迁移。

Come across what seems like a common scenario but not been able to find a solution遇到看似常见但无法找到解决方案的情况

Base class libraries have static HttpContext Request/Response/Session references.基本 class 库具有 static HttpContext 请求/响应/会话引用。 I know I could refactor out these dependencies but that's a massive job so;我知道我可以重构这些依赖项,但这是一项艰巨的工作;

Using a simple example;使用一个简单的例子;

public class QueryStringHelper : IQueryStringHelper
{
    public string GetValue(string key) => HttpContext.Current.Request[key];
}

HttpContext doesn't exist as we know it in System.Web and needs to be injected in via IHttpContextAccessor. HttpContext 不存在,因为我们在 System.Web 中知道它,需要通过 IHttpContextAccessor 注入。

public class QueryStringHelper : IQueryStringHelper
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public QueryStringHelper(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string GetValue(string key) => _httpContextAccessor.HttpContext.Request[key];
}

Using this base class library from a .NET Core application is simple enough, registering with the DI container使用来自 .NET 核心应用程序的基本 class 库非常简单,向 DI 容器注册

builder.Services.AddHttpContextAccessor();

BUT.. how can we use this base class from a .NET Framework application?但是..我们如何从 .NET 框架应用程序中使用这个基础 class? Is this completely the wrong approach, or is there a way to achieve this?这完全是错误的方法,还是有办法做到这一点?

There are massive fundamental differences in those classes between .NET Framework and .NET Core. .NET Framework 和 .NET Core 之间的这些类存在巨大的根本差异。

For example, the .NET Framework session can hold any object, whereas the .NET Core session can only store strings. For example, the .NET Framework session can hold any object, whereas the .NET Core session can only store strings.

You cannot simply swap out the classes and expect your code to work in both.您不能简单地交换类并期望您的代码在两者中都可以工作。 If you really need your project to work across .NET Framework and .NET Core, you will need to multi-target it, and use conditional compilation to account for the differences.如果您确实需要您的项目跨 .NET 框架和 .NET 核心工作,您将需要多目标,并使用条件编译来解决差异。

Multi-targeting for NuGet Packages in your project file | 项目文件中 NuGet 包的多目标 | Microsoft Docs 微软文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM