Accessing HttpContext in ASP.NET Core 2.2 Class library

Viewed 9801

I need to access the HttpContext.Current in a class library in ASP.NET Core 2.2

HttpContext.Current.Request.Url.ToString().Contains("SAMLart")

I'm attempting to port the code over and HttpContext doesn't even have Current in a main web project when I attempt to just try using a method in a HomeController.

1 Answers

Register IHttpContextAccessor in the Startup class as follows:

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

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}

Then in your class libray

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