Defining a User with User.Identity.Name in controller constructor

前端 未结 4 1752
终归单人心
终归单人心 2021-02-03 13:15

For my actions that are going to interact with the User\'s account, I would like to create a \"TheUser\" object in addition to adding that object to \"ViewData[\"TheUser\"]\" as

4条回答
  •  迷失自我
    2021-02-03 13:42

    Does the User have to be instantiated for every Controller action or just specific ones?

    If you create an ActionFilterAttribute, you do have access to the Controller context. Not sure if that is true for AuthorizationFilters, but you could try something like this:

    public class MyCustomFilter: ActionFilterAttribute
    {
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewData["TheUser"] = User.Identity.IsAuthenticated ? UserRepository.GetUser(User.Identity.Name) : null;
            base.OnActionExecuting(filterContext);
        }
    }
    

    Then, attach this to the necessary controller actions.

提交回复
热议问题