Accessing HTTPContext in Core

HttpContext has had a bit of a shifting around in 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 :

public async Task<bool> LoggedIn()
	var myUser = HttpContext.User;
	return myUser.Identities.Any(x => x.IsAuthenticated);

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 :

public void ConfigureServices(IServiceCollection services)
	services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

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 :

public class UserService : IUserService
	private readonly IHttpContextAccessor _httpContextAccessor;

	public UserService(IHttpContextAccessor httpContextAccessor)
		_httpContextAccessor = httpContextAccessor;

	public bool IsUserLoggedIn()
		var context = _httpContextAccessor.HttpContext;
		return context.User.Identities.Any(x => x.IsAuthenticated);

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.

Join over 3.000 subscribers who are receiving our weekly post digest, a roundup of this weeks blog posts.
We hate spam. Your email address will not be sold or shared with anyone else.


  1. It would be quite usefull to follow up this article with how to access IHttpSessionStateBase inside a helper/service class.

Leave a Reply

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