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

前端 未结 4 1751
终归单人心
终归单人心 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 13:48

    I created a custom base Controller class and added a "CurrentUser" property to it.

    In the Initialize method, I placed the logic to get the user and then add it to the ViewData and the "CurrentUser" property of the controller.

    I had my controllers inherit the custom base Controller class and I was able to reference "CurrentUser" variable anywhere in the controller:

    public class CustomControllerClass : Controller
    {
        public User CurrentUser { get; set; }
    
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
    
            if (requestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string userName = requestContext.HttpContext.User.Identity.Name;
                CurrentUser = UserRepository.GetUser(userName);
            }
    
            ViewData["CurrentUser"] = CurrentUser;                
        }
    }
    

提交回复
热议问题