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 :

[HttpGet]
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.AddMvc();
	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.

6 thoughts on “Accessing HTTPContext in ASP.NET Core”

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

    Reply
  2. One quick question is , why services.AddSingleton ? and why not AddScoped? As per my understanding Singleton instance will share the context accross all the HttpRequest [which i guess we dont want] , it should be AddScoped so that for each HttpRequest we can get the new context and not the previous requests context. Please correct me what am I missing here.

    Reply
    • The accessor object (IHttpContextAccessor) will be singleton, but when you call _httpContextAccessor.HttpContext it will be scoped. Basically like a factory pattern. The factory itself is singleton (So the thing giving you the context), but the context itself is not.

      Reply

Leave a Comment