Read ControllerBase.User in constructor

2020-04-21 02:32发布

I'd like to have a base controller that should set auth variables for every controller action:

_claimsIdentity = User.Identity as ClaimsIdentity;
_userId = claimsIdentity.FindFirst("ID")?.Value;

Unfortunately ControllerBase.User is null in the constructor and there's no Initialize method on ControllerBase to override as suggested here. How can I make a base controller with these values already set for every action?

1条回答
爷的心禁止访问
2楼-- · 2020-04-21 02:54

The controller is initialized earlier in the pipeline before the User property has been set. This means that it will be null if you try to access it in the constructor.

By the time an action is invoked, the framework would have already assigned the necessary values extracted from the request. So it is advisable to access User property from within an action.

As an alternative to setting fields on your base controller constructor, you could achieve what you're looking for with properties. e.g.:

protected ClaimsIdentity ClaimsIdentity => User.Identity as ClaimsIdentity;
protected string UserId => ClaimsIdentity.FindFirst("ID")?.Value;

And access them from within an action of the derived child classes.

The child classes wouldn't know any different - The only difference is the naming convention is different on properties, but if this really upsets you, you could always use the same names you had before.

查看更多
登录 后发表回答