Error No service for type 'Microsoft.AspNetCore.Http.Ihttpcontextaccessor' has been Registered

Asked

Viewed 1,380 times

-1

To help those who are going through the same problem (ANSWER BELOW).

Scenario: I am developing an ASP.NET CORE MVC application where I am working with Httpcontextaccessor and the error occurs below.

Error:

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' has been registered.

1 answer

4

The problem is because by default the IHttpContextAccessor no longer comes connected.

To solve this problem we must manually connect/log the service within the class Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Adicione eessa linha para que seu projeto volte a funcionar normalmente.
    services.AddSession();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.