Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 556
yosbel Avatar asked Aug 05 '26 18:08

yosbel


2 Answers

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;
like image 134
James Ellis-Jones Avatar answered Aug 07 '26 12:08

James Ellis-Jones


For HttpContext to be valid, the program flow calling your class must originate in a controller or some middleware component. You could just pass a reference to HttpContext to your class.

like image 20
Clint B Avatar answered Aug 07 '26 14:08

Clint B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!