ASP.NET控制器基类User.Identity.Name

Mas*_*rfu 4 c# asp.net-mvc abstract-class controller master-pages

如在描述的这篇文章中,我创建一个抽象基类控制器,以便能够从控制器的数据传递到master.page.在这种情况下,我想在我的数据库中查找用户,查询User.Identity.Name(仅当他登录时).

但是,我注意到在这个抽象基类中,User属性总是如此null.要做到这一点,我该怎么办?

非常感谢

小智 7

正如Paco建议的那样,在您尝试使用它之前,viewdata尚未初始化.

尝试重写Controller.Initialize():

public abstract class ApplicationController : Controller
{
    private IUserRepository _repUser;

    public ApplicationController()
    {
    }

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        _repUser = RepositoryFactory.getUserRepository();
        var loggedInUser = _repUser.FindById(User.Identity.Name);
        ViewData["LoggedInUser"] = loggedInUser;
    }
}
Run Code Online (Sandbox Code Playgroud)