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

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

HttpContext.Current.User.Identity.Name

Note the .Current that was missing from your call.

Method 2

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.

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

Method 4

use

Page.User.Identity.Name

Method 5

You’re in a controller so use the following:

ControllerContext.HttpContext.Current.User.Identity.Name


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x