asp.net-mvchttpcontextcontrollers

accessing HttpContext.Request in a controller's constructor


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?


Solution

  • The Controller is instantiated significantly prior to the point where the Index action is invoked, and at the moment of construction HttpContext is indeed unavailable. What's wrong with referencing it in your controller method Index?