ASP.NET Controller Base Class User.Identity.Name

2019-03-30 17:40发布

As described in this post, I created an abstract base controller class in order to be able to pass data from a controller to master.page. In this case, I want to lookup a user in my db, querying for User.Identity.Name (only if he is logged in).

However, I noticed that in this abstract base class the User property is always null. What do I have to do to get this working?

Thanks a lot

5条回答
三岁会撩人
2楼-- · 2019-03-30 17:46

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

HttpContext.Current.User.Identity.Name
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-30 17:59

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;
    }
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-30 18:00

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..

查看更多
在下西门庆
5楼-- · 2019-03-30 18:00

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

查看更多
淡お忘
6楼-- · 2019-03-30 18:13

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

查看更多
登录 后发表回答