ASP.NET Controller Base Class User.Identity.Name

╄→尐↘猪︶ㄣ 提交于 2019-12-03 16:23:04

As Paco suggested, the viewdata isn't initialized till after you are trying to use it.

Try overriding Controller.Initialize() instead:

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

To use the user, you should get the current page from

HttpContext.Current.User.Identity.Name

By setting authentication to Windows in web.config, you can get the user with User.Identity.Name

I use Page class on my static Utlilites classes. Like that;

Page P = (Page)HttpContext.Current.Handler;

and i can get all properties via the P object for the current requested page..

Have you tried this: ControllerContext.HttpContext.Current.User.Identity.Name?

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