Mike A Mike A - 3 years ago 85
ASP.NET (C#) Question

In ASP.NET MVC 5, what method set the User object?

I have a application that uses multiple controller inheritance. I override the

Initialize(RequestContext requestContext)
in multiple levels of my inheritance , but each time I override the
Initialize
method, I call
base.Initialize(requestContext);


[Authorize]
public class FirstBaseController: Controller
{
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// Set few custom global things
}

}

public class SecondBaseController: FirstBaseController
{

protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// At this point, I am expecting that the `User` object is already set by identity
//check the claims value here.
}
}


However if I try to access the
User
object from inside the
Initialize
method I found it not yet set!

At what point in time does the framework sets the
User
object? Which method before the action method I can override where the
User
object will be set already?

I don't want to use action filter here because I want this logic to get executed on every request.

Answer Source

This is going to vary somewhat depending on what method you are using for authentication, but you should be safe to access the User in the `OnActionExecuting' method.

You could also implement that as an action filter and apply that filter to each controller (or to just a base-class controller - it will "carry through" to any controllers that inherit from it)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download