I need to access current HttpContext
in a static method or a utility service.
With classic ASP.NET MVC and System.Web
, I would just use HttpContext.Current
to access the context statically. But how do I do this in ASP.NET Core?
I need to access current HttpContext
in a static method or a utility service.
With classic ASP.NET MVC and System.Web
, I would just use HttpContext.Current
to access the context statically. But how do I do this in ASP.NET Core?
HttpContext.Current
doesn't exist anymore in ASP.NET Core but there's a newIHttpContextAccessor
that you can inject in your dependencies and use to retrieve the currentHttpContext
:Necromancing.
YES YOU CAN
Secret tip for those migrating large
junkschunks (sigh, Freudian slip) of code.The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In
public class Startup
add a property
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
Then in Configure
add the DI Parameter
IServiceProvider svp
, so the method looks like:Next, create a replacement class for System.Web:
Now in Configure, where you added the
IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)and set HostingEnvironment.IsHosted to true
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in
Application_Start
in global.asax.I stress again, this only works if you actually added
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
And then calling HttpContext.Configure in Startup->Configure
The most legit way I came up with was by injecting IHttpContextAccessor in your static implementation as follow:
Then assigning the IHttpContextAccessor in the Startup Configure should do the job.
I guess you should also need to register the service singleton:
Just to add to the other answers...
In ASP.NET Core 2.1, there's the
AddHttpContextAccessor
extension method, that will register theIHttpContxtAccessor
with the correct lifetime.