Accessing the HttpContext from the Constructor of a Controller or a Dependency

Full source code here.

There are times when you may need to access the HttpRequest from places that it is not normally available such as the constructor of a controller or the constructor of a service that is built by dependency injection.

Take the example of a ValuesController that relies on a NumberGeneratorService, where both need to know the Host used in the request.

But you can’t just access the Host via the Request in either case. It is not yet available in the lifetime of the controller and it will not be available at all in the life of the service. (By the time you reach the action method of the controller you will have access to it.)

Fortunately there is a way to get at it using the HttpContextAccessor.

In Startup.cs add the following -

1public void ConfigureServices(IServiceCollection services)
3    services.AddScoped<INumberGeneratorService, NumberGeneratorService>();
4    services.AddHttpContextAccessor();
5    //snip..

Pass IHttpContextAccessor to the constructor of the ValuesController

1public ValuesController(IHttpContextAccessor httpContextAccessor, INumberGeneratorService numberGeneratorService)
3    _numberGeneratorService = numberGeneratorService;
4    Console.WriteLine($"Request.Host inside constructor of controller : {httpContextAccessor.HttpContext.Request.Host.Value}");

Do the same to the constructor of the the NumberGeneratorService -

1public NumberGeneratorService(IHttpContextAccessor httpContextAccessor)
3    _httpContextAccessor = httpContextAccessor;
4    Console.WriteLine($"Request.Host inside service : {httpContextAccessor.HttpContext.Request.Host.Value}");

Now you have full access to everything about the request in controller’s constructor and the services you depend on.

In another post I’ll show a more practical use of this when I want to use the dependency injection with two implementations of an interface, HttpContextAccessor will help me choose between them based on the request.

Full source code here.

comments powered by Disqus