Read ControllerBase.User in constructor

隐身守侯 提交于 2019-12-02 06:55:38
Kirk Larkin

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!