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

前端 未结 4 1817
终归单人心
终归单人心 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:40

    I setup my base controller in a similar way using the constuctor method, and I was able to read this User info on the following mannner. Note: I only store the UserId, not the User object, but the point of my code is to show how you can get the required info in the contriuctor method.

    public abstract class BaseController : Controller
    {
        int _UserId = 0;
    
        public int UserId
        {
            get { return _UserId; }
            set { _UserId = value; }
        }
    
        public BaseController()
        {
            var userFromAuthCookie = System.Threading.Thread.CurrentPrincipal;
    
            if (userFromAuthCookie != null  && userFromAuthCookie.Identity.IsAuthenticated) // && !String.IsNullOrEmpty(userFromAuthCookie.Identity.Name))
            {
                busUser userBO = AceFactory.GetUser();
                string userNameFromAuthCookie = userFromAuthCookie.Identity.Name;
                _UserId = userBO.GetUserIdByUsername(userNameFromAuthCookie);
            }
        }
    

提交回复
热议问题