views:

8564

answers:

6

In forms model, I used to get current logged in user by

Page.CurrentUser

How do I get current user inside a controller class in ASP.NET MVC?

A: 

I use:

Membership.GetUser().UserName

Not sure this will work in MVC but it's worth a shot :)

Sean
Where does this Membership class come from? IntelliSense does not recognize it by default.
Serhat Özgel
The System.Web.Security namespace. I'm not positive this is useful in MVC but I use it with the login controls for Web Forms.
Sean
It's useful in any ASP.NET application that uses the Membership providers.
jamiebarrow
+7  A: 

try HttpContext.Current.User

UPDATE (reading comment):

Public Shared Property Current() As System.Web.HttpContext
Member of System.Web.HttpContext

Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.

Return Values:
The System.Web.HttpContext for the current HTTP request

.

dove
Apparently HttpContext does not have a property named "Current".
Serhat Özgel
I believe you two are talking about two different things.System.Web.HttpContext and the static property:System.Web.Mvc.Controller.HttpContext (Which does not have a "Current" property.
Jeff Sheldon
That worked on a non-MVC environment, just what I needed. Thanks! :)
Wagner Danda da Silva
+13  A: 

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.

Haacked
"or you could just call User as I think it's a property of ViewPage" - So do you mean use Page.user when you're in the view?
mawaldne
+3  A: 

I realize this is really old, but I'm just getting started w/ MVC.Net, so I thought I'd stick my two cents in:

Request.IsAuthenticated tells you if the user is authenticated. Page.User.Identity gives you the identity of the logged-in user.

jrb
+6  A: 

I found that 'User' works, ie. User.Identity.Name or User.IsInRole("Administrator")... Hope this helps although a bit late.

Thanks, this actually did help!
thebrokencube
A: 

getting logged in username: System.Web.HttpContext.Current.User.Identity.Name

tifoz

related questions