You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Essentially, it just boils down to adding an explanation of what IHttpContextAccessor does, why it's useful, and when it should be used (and when it shouldn't be :))
This StackOverflow post explains the challenge that ASP.NET developers may have coming to ASP.NET Core without an HttpContext.Current API and how IHttpContextAccessor can help. This GitHub issue explains that it's not in the DI container by default.
Here are some notes I took on this one previously during a code porting project:
System.Web.HttpContext is not used in ASP.NET Core. A new ASP.NET Core version of HttpContext is available (in the Microsoft.AspNetCore.Http namespace), but it doesn’t have a .Current static property. This is because ASP.NET Core does not depend on global statics, retrieving state by dependency injection instead.
To fix code that was using HttpContext.Current, one of the following approaches can be used:
If the code using HttpContext.Current is in middleware or a controller, then the current HttpContext can be retrieved directly from the dependency injection container, instead.
If the code using HttpContext.Current is called from a controller or middleware component, then the current context can be passed as a parameter.
If neither of those works, a static helper can retrieve an IHttpContextAccessor from dependency injection and use that to query for the current HttpContext.
For new development, options 1 and 2 should usually work. In the case of some projects, though, there may be many uses of HttpContext.Current in existing code that would take a lot of changes to re-write to use option 2. To deal with this, we can use option 1 where possible and then add IHttpContextAccessor to the dependency injection container (using AddHttpContextAccessor since it is not there by default) and create a helper class that the Startup.Configure method populates with an instance of IHttpContextAccessor. Code without direct access to the DI container can call a static method on that class to get the IHttpContextAccessor.
@mjrousos can you provide notes/draft on this?
The text was updated successfully, but these errors were encountered: