Search code examples
asp.net-corehttpcontext

Get HttpContext in AspNet Core 1.0.0 outside a Controller


I need to get the HttpContext in AspNet Core outside a controller. In the older AspNet 4 I could get it using HttpContext.Current, but it seems to be removed in the new AspNet. The only workaround I have found is resolving an IHttpContextAccessor by dependency injection and asking it the HttpContext, but to inject the IHttpContextAccessor I need to add IHttpContextAccessor as a singleton in the application Startup:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

I researched it and this is the only way I found. I google it and IHttpContextAccessor was removed as a default in the dependency resolver because it is very heavy dependency. Is there any other way to achieve this?

Edit: I wonder if instead of adding it as a Singleton to the dependency resolver, I could get in that same place the instance of the HttpContextAccessor to save it in my own singleton class?


Solution

  • If you are porting a legacy application to ASP.Net Core that is reasonably complex, it would require totally reengineering to work properly with the .Net Core DI system. If you don't want to do this, you can 'cheat' by making this functionality global again in a Service Locator. To do this (which is not recommended if you can avoid it):

    public class RequestContextManager
    {
      public static RequestContextManager Instance { get; set; }
    
      static RequestContextManager()
      {
        Instance = new RequestContextManager(null);
      }
    
      private readonly IHttpContextAccessor contextAccessor;
    
      public RequestContextManager(IHttpContextAccessor contextAccessor)
      {
        this.contextAccessor = contextAccessor;
      }
    
      public HttpContext CurrentContext
      {
        get
        {
          if (contextAccessor == null)
            return null;
          return contextAccessor.HttpContext;
        }
      }
    }
    
    // In Startup.cs
    public void Configure(IApplicationBuilder app,...)
    {
      ...
      RequestContextManager.Instance = new RequestContextManager(app.ApplicationServices.GetService<IHttpContextAccessor>());
      ...
    }
    
    // In your code
    var httpContext = RequestContextManager.Instance.CurrentContext;