4

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.

sajadre
  • 1,141
  • 2
  • 15
  • 30

1 Answers1

6

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..
    }
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Seven
  • 134
  • 3
  • 5
    Well, I do have a class library - so in a class library there is NO startup... thoughts? –  Jan 16 '19 at 23:04