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


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>();
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.