在 ASP.NET Core 2.2 Class 库中访问 HttpContext

Accessing HttpContext in ASP.NET Core 2.2 Class library

我需要在 ASP.NET Core 2.2

的 class 库中访问 HttpContext.Current
HttpContext.Current.Request.Url.ToString().Contains("SAMLart")

我正在尝试移植代码,但 HttpContext 在主 Web 项目中甚至没有 Current 当我试图尝试使用 HomeController 中的方法时。

Startupclass中注册IHttpContextAccessor如下:

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}

然后在你的 class 库中

public class Test 
{
    private IHttpContextAccessor _httpContextAccessor;
    public Test(IHttpContextAccessor httpContextAccessor)
    {
         _httpContextAccessor = httpContextAccessor;
    }
    public void Foo()
    {
        _httpContextAccessor.HttpContext.Request.Path..
    }
}