简体   繁体   English

如何从控制器获取User.Identity.Name?

[英]How to get User.Identity.Name from a controller?

I want to have some viewData info across all my views so I am following this tutorial 我想在所有视图中都包含一些viewData信息,因此我正在关注本教程

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

So I made my own applicationController but I need to get the UserName from the user. 因此,我制作了自己的applicationController,但需要从用户那里获取UserName。

Yet when I do this "HttpContext.User.Identity.Name" in the constructor it is always null. 但是,当我在构造函数中执行“ HttpContext.User.Identity.Name”时,它始终为null。 I am not sure why though. 我不确定为什么。

Thanks 谢谢

Ok the base thing did the trick. 好的,基本的事情就解决了。

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

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. 太多了,我应该缓存它,但是我不确定如何缓存。

HttpContext.Current.User.Identity.Name  

请注意您的呼叫中缺少的.Current

Try initializing stuff in the ApplicationController's Initialize method, HttpContext isn't avaliable in the constructor. 尝试初始化ApplicationController的Initialize方法中的内容,但HttpContext在构造函数中不可用。 Make sure to call base.Initialize() or you can get some interesting results. 确保调用base.Initialize(),否则您会得到一些有趣的结果。

Which specific property that you are accessing is null? 您要访问的哪个特定属性为null? You might want to check that User.Identity.IsAuthenticated == true before checking the Name property. 您可能需要在检查Name属性之前检查User.Identity.IsAuthenticated == true。 Also make sure that forms authentication is enabled and that you have indeed logged into the site first. 另外,请确保已启用表单身份验证,并且您确实确实已经首先登录了该站点。

采用

Page.User.Identity.Name

您在控制器中,请使用以下命令:

ControllerContext.HttpContext.Current.User.Identity.Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM