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

心不动则不痛 提交于 2019-12-02 21:12:11

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;                
    }
}

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);
        }
    }
public abstract class YourController : Controller
{
    public YourController()
    {
        var user = System.Threading.Thread.CurrentPrincipal;

        TheUser = User.Identity.IsAuthenticated ? UserRepository.GetUser(user.Identity.Name) : null;

        ViewData["TheUser"] = TheUser;  
    }
}

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.

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