2

I'm trying to solve the problem: when a user is being logged into a WebSite (via user control .ascx stored on the Master Page), it's name is being stored in a Page.User.Identity.Name property. OK, but how to retrieve that user name in the controller ? Is it possible without registering System.Security.Principal namespace in the controller ? In the other words - the controller must know whose user wants to do some action (e.g. change account data). I could store it's name in the Html.Hidden control on each View but I don't want to have a mess in my Views

2
  • Are you mixing MVC and WebForms? Commented Apr 12, 2010 at 17:26
  • No, I don't. I just want to have access to the User name anytime I need. I don't use Membership class Commented Apr 12, 2010 at 17:29

3 Answers 3

5

IPrincipal User is one of the members in your controller (it is a property), so all you have to do to get the name of the currently logged in user in your controller method is

string userName = User.Identity.Name
Sign up to request clarification or add additional context in comments.

Comments

1

Robert's answer is correct. Another alternative is to use the Thread class:

System.Threading.Thread.CurrentPrincipal.Identity.Name

Comments

0

Have you considered using the Session to store user-related data?

3 Comments

One of the benefits of ASP.NET MVC is that it eliminates the need to encode large amounts of Session data in the web page.
@Robert - 'encode large amounts of Session data in the web page'. Unsure what you mean here. I was referring to the Session in memory in IIS. Sounds like you're referring to webforms ViewState? I'm confused by your comment. :)
Mmm, think you're right. Got my terminology confused. That said, I have yet to use Session in an ASP.NET MVC app, given the ability to use ViewModel classes, ViewData and data binding to do the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.