InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

Posted by Blake on 5/23/2017
)

Problem:

You may receive the following exception when trying to access the HttpContext in an ASP.Net Core application.

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

Solution:

This error typically indicates that the HttpContext hasn't been wired up to be injected to wherever it is that it's being called from. In order to register the HttpContextAccessor you will need to register it in the ConfigureServices method in your startup file (typically Startup.cs or Startup.vb)

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        // This is the line you're interested in
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }