Read ControllerBase.User in constructor

前端 未结 1 1409
难免孤独
难免孤独 2021-01-26 23:39

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

_claimsIdentity = User.Identity as ClaimsIdentity;
_userId = clai         


        
1条回答
  •  伪装坚强ぢ
    2021-01-27 00:33

    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.

    0 讨论(0)
提交回复
热议问题