ASP.NET Controller Base Class User.Identity.Name

浪尽此生 提交于 2020-01-31 18:16:28

问题


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


回答1:


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



回答2:


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

HttpContext.Current.User.Identity.Name



回答3:


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




回答4:


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:


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



来源:https://stackoverflow.com/questions/426110/asp-net-controller-base-class-user-identity-name

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