Reputation: 11990
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.
Upvotes: 2
Views: 887
Reputation: 50728
Using JustDecompile to see the references, the User property really navigates up to the RequestContext
reference passed into Initialize (which has a reference to HttpContext
). So in Initialize, if the requestContext
variable passed into the method has a property HttpContext
that is null or HttpContext.User
reference is null, then the current user is not available in Initialize()
.
OnActionExecuting is a good place like @Eric said.
Upvotes: 1
Reputation: 60498
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)
Upvotes: 1