accessing HttpContext.Request in a controller's constructor

Viewed 46615

I'm following this ASP.NET MVC tutorial from Microsoft:

My code is slightly different, where I'm trying to access HttpContext.Request.IsAuthenticated in the controller's constructor.

namespace SCE.Controllers.Application
{
    public abstract class ApplicationController : Controller
    {
        public ApplicationController()
        {
            bool usuario = HttpContext.Request.IsAuthenticated;
        }           
    }
}

The problem is that HttpContext is always null.

Is there a solution to this?

6 Answers

enter image description hereWith the answer I am posting here, you cannot access IsAuthenticated, but you can access some stuffs related to HttpContextRequest (see in image),

I needed session value in constructor.

You can use IHttpContextAccessor as below:

public ABCController(IHttpContextAccessor httpContextAccessor)   
{
     //do you stuff with httpContextAccessor,  

     // This gives session value
     string abc = httpContextAccessor.HttpContext.Session.GetString("Abc");
}

and in startup.cs, you need to configure,

services.AddHttpContextAccessor();

It is possible to get the HttpContext using IHttpContextAccessor injected into class constructor. Before doing so, you will need first to register the corresponding service to the service container in Startup.cs class or Program.cs such as below.

services.AddHttpContextAccessor(); // Startup.cs

builder.Services.AddHttpContextAccessor(); // Program.cs

Right after that, you can inject the IHttpContextAccessor interface in whererever method or class constructor.

 private bool isAuthenticated { get; set; }

    public ConstructorName(IHttpContextAccessor accessor)
    {
        var context = accessor.HttpContext;

        isAuthenticated = context.User.Identity.IsAuthenticated;
    }
Related