I have a base Controller on my ASP.NET MVC4 website that have a Constructor simple as this:
public class BaseController : Controller
{
protected MyClass Foo { get; set; }
public BaseController()
{
if (User.Identity.IsAuthenticated))
{
Foo = new MyClass();
}
}
}
However I cannot access User
here. It's null
. But on my inherited Controllers it's fine.
Thanks
Controller instantiation will occur before authorisation takes place. Even if your MVC application calls
RenderAction()
several times and you end up creating say, five different controllers, those five controllers will be created before any OnAuthorization takes place.The best approach to deal with these situations is to use Action Filters. The Authorize Attribute is fired early and may well be suited to your situation.
First, let's create an AuthorizationFilter.
Now let's update our Controller
In this case I would override Controller Initialize method: