ASP.NET Core introduces the IHttpContextAccessor interface as a way to provide access to the HttpContext. Before you can use it, you have to register it at application startup inside the IServicesCollection. During a code review I noticed that it was registered like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddMvc(); | |
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>(); | |
} |
This turns out to be wrong. The IHttpContextAccessor should be registered as a singleton. So the correct code is the following:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddMvc(); | |
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); | |
} |
More information: https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/