Using HttpContext Request/Response/Session from NetStandard2.0 library

Viewed 290

Upgrading a very large .NET Framework 4.8 enterprise application consisting of 70+ applications and 200+ base class libraries (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. 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. 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.

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

builder.Services.AddHttpContextAccessor();

BUT.. how can we use this base class from a .NET Framework application? Is this completely the wrong approach, or is there a way to achieve this?

1 Answers

There are massive fundamental differences in those classes between .NET Framework and .NET Core.

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.

Multi-targeting for NuGet Packages in your project file | Microsoft Docs

Related