如何从一个控制器获得User.Identity.Name?控制器、User、Name、Identity

2023-09-06 14:38:34 作者:太阳请晒黑我父母的白发

我想有所有我的看法有些可视数据信息,所以我下面这个教程

I want to have some viewData info across all my views so I am following this tutorial

http://www.asp.net/LEARN/mvc/教程-13-cs.aspx

所以我做了我自己的ApplicationController,但我需要得到用户的用户名。

So I made my own applicationController but I need to get the UserName from the user.

然而,当我在构造函数中做到这一点HttpContext.User.Identity.Name它总是空。我不知道为什么,虽然。

Yet when I do this "HttpContext.User.Identity.Name" in the constructor it is always null. I am not sure why though.

感谢

确定的基础的东西做的伎俩。

Ok the base thing did the trick.

  protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        Guid userId = coursesS.GetUserId(HttpContext.User.Identity.Name);
    }

所以,似乎工作。唯一的一点现在似乎要通过这个的两倍。就像我登录,它似乎做这个的两倍。我猜测,因为这就像把那个code的每一个动作的等价物。当我装上我的网站所有的部分观点,称他们在我的控制器它这样做。

So that seems to work. The only thing now is it seems to go through this twice. Like I log in and it seems to do the this twice. I am guessing since this is like the equivalent of putting that code in every action. When I am loading up all these partial view on my site by calling them in my controller it does this.

这么多,我应该缓存,但我不知道怎么虽然。

So many I should cache it but I am not sure how though.

推荐答案

尝试到ApplicationController中的初始化方法的初始化的东西,HttpContext的是暂不提供在构造函数中。确保调用base.Initialize(),或者你可以得到一些有趣的结果。

Try initializing stuff in the ApplicationController's Initialize method, HttpContext isn't avaliable in the constructor. Make sure to call base.Initialize() or you can get some interesting results.