views:

125

answers:

2

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?

+1  A: 

instead of putting your HttpContext.Request.IsAuthenticated in Controller level you should put it in Controller Base class that will be inherited in all of your controller with an override method of OnActionExecuted() method.

In your Controller base you should have

public class BaseController : Controller
{
    public override void OnActionExecuted(ActionExecutedContext ctx) {
        base.OnActionExecuted(ctx);
        ViewData["IsAuthenticated"] = HttpContext.Request.IsAuthenticated;
    }
}

and all your Controller should inherit the BaseController class

publick class ApplicationController : BaseController

now you should get the ViewData["IsAuthenticated"] in your Master page.

Edit

With the link you have given, and relating to what you have done, your ApplicationController is a Page Controller, not a Base Controller. What you are doing is wrong, since in the example, ApplicationController is a Base Controller that is inherited by the HomeController but what you have done is you are placing the Action method inside your base controller which is the ApplicationController so your Action Index method will not be invoked when you call any page (Index page) that is not from the ApplicationController.

rob waminal
+2  A: 

I've never needed to use a contructor for a Controller. I imagine that 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?

spender
only with DI in place controller constructors contain code and typically it is just one line _repository = repository
mare