How to get User.Identity.Name from a controller?

2020-03-30 04:20发布

问题:

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

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.

Yet when I do this "HttpContext.User.Identity.Name" in the constructor it is always 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.

回答1:

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.



回答2:

HttpContext.Current.User.Identity.Name  

Note the .Current that was missing from your call.



回答3:

Which specific property that you are accessing is null? You might want to check that User.Identity.IsAuthenticated == true before checking the Name property. Also make sure that forms authentication is enabled and that you have indeed logged into the site first.



回答4:

use

Page.User.Identity.Name


回答5:

You're in a controller so use the following:

ControllerContext.HttpContext.Current.User.Identity.Name