Accessing HTTPContext in ASP.net Core

HttpContext has had a bit of a shifting around in ASP.net core. While everyone has their own ideas on best practices, it’s a bit of a consensus that the usage of calling “HttpContext.Current” outside the scope of a controller (For example in a service class) was getting out of hand. It also made testing just that little bit harder.

So how to do it now? There are two ways.

Inside Controllers

Inside a controller, you can still access HttpContext by doing the following :

No, there is nothing special that I have done to access the Property “HttpContext”, it’s just available when inheriting from the base “Controller” class. Simple!

Inside Services

Inside services is a little tricker, but still possible. Note that you may want further abstraction away from directly accessing an HTTPContext, for example if you are using it for “Sessions” you may want to abstract it away incase you scale your servers horizontally and you will no longer be able to use the HTTP Session object within C#. But if you don’t think you’ll need that, read on!

First in your startup.cs, you need to register IHttpContextAccessor as a service like so :

In earlier versions of .net Core, IHttpContextAccessor was automatically registered. This was removed and announced here. So you need to register it manually if you intend to use this inside services.

When you create a helper/service class, you can then inject in the IHttpContextAccessor and use it. It would look like something not too dissimilar to this :

Unfortunately if you have accessed HttpContext throughout your old .net 4.5 code and are looking to upgrade to .net Core, you will have to do a bit of work to get it working again. But it’s worth it for the nice clean approach to DI and better testability.

Leave a Reply

Your email address will not be published. Required fields are marked *