How to get the current user in ASP.NET MVC
Asked Answered
C

21

278

In a forms model, I used to get the current logged-in user by:

Page.CurrentUser

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

Currier answered 4/11, 2008 at 21:24 Comment(0)
S
272

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.

Sven answered 4/11, 2008 at 23:19 Comment(3)
"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?Wishbone
Yes, you can use it like, "Hi, @User.Identity.Name!" in the cshtml.Exhortation
So this is how you explain it to a newbie? Is it hard to write @User.Identity.Name as an example? -1Fruiter
B
211

I found that User works, that is, User.Identity.Name or User.IsInRole("Administrator").

Barrio answered 27/5, 2009 at 15:2 Comment(2)
Just to add to this, if you're working in a class outside of a form you'll either need to Imports System.Web and further qualify with with HttpContext.Current.User.Identity.Name, or directly qualify using the full syntax: System.Web.HttpContext.Current.User.Identity.NameHolston
Works inside a Controller and if using a ViewModel either inherit from Controller or follow Paul's suggestion.Estellestella
C
62

Try HttpContext.Current.User.

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

Cordite answered 4/11, 2008 at 21:30 Comment(3)
Apparently HttpContext does not have a property named "Current".Currier
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.Schroeder
That worked on a non-MVC environment, just what I needed. Thanks! :)Siloum
P
40

You can get the name of the user in ASP.NET MVC4 like this:

System.Web.HttpContext.Current.User.Identity.Name
Principally answered 22/9, 2013 at 19:38 Comment(1)
If you are getting this error 'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found, I would suggest making an absolute call like this, System.Web.HttpContext.Current.User.Identity.Name.Whispering
C
21

I realize this is really old, but I'm just getting started with ASP.NET MVC, 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.
Curarize answered 25/3, 2009 at 1:42 Comment(0)
E
16

I use:

Membership.GetUser().UserName

I am not sure this will work in ASP.NET MVC, but it's worth a shot :)

Exhortation answered 4/11, 2008 at 21:29 Comment(4)
Where does this Membership class come from? IntelliSense does not recognize it by default.Currier
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.Exhortation
It's useful in any ASP.NET application that uses the Membership providers.Jegger
This will actually make a database request. HttpContext.Current.User doesn't.Susan
C
11

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

Caughey answered 8/9, 2010 at 12:50 Comment(0)
F
10

UserName with:

User.Identity.Name

But if you need to get just the ID, you can use:

using Microsoft.AspNet.Identity;

So, you can get directly the User ID:

User.Identity.GetUserId();
Fogle answered 12/1, 2017 at 13:44 Comment(2)
This method return a System.GuidFogle
User.Identity.Name is an instance of System.Security.Principal.IPrincipal which does not have an id property... Is this User different from User.Identity.GetUserId 's User objectTroop
I
9

In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use

WebSecurity.CurrentUserId

once you add a using statement

using System.Web.Security;
Internode answered 22/6, 2013 at 19:12 Comment(2)
Unfortunately this doesn't seem to work anymore in MVC 5. Not sure why =/Jablon
Only System.Security.Principal.WindowsIdentity.GetCurrent().Name works in MVC 5. However that pulls up the domain name with the username. i.e. domain\usernameStutz
A
9

We can use following code to get the current logged in User in ASP.Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

Also

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'
Arithmomancy answered 23/1, 2018 at 23:28 Comment(3)
hi @rajbaral This worked for me, what if i want to extract the other information from the current user from the db, example address field.Paganize
@Paganize you need to write a method to get UserProfile from your AD using that userNameArithmomancy
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; This is just straight up incorrect information. This call will get you the identity of the Application Pool and not of the web user.Ayannaaycock
M
6

This page could be what you looking for:
Using Page.User.Identity.Name in MVC3

You just need User.Identity.Name.

Marco answered 13/11, 2011 at 8:51 Comment(1)
This works only inside a Controller; or if your ViewModel inherits from ControllerEstellestella
T
5

Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.

This will get the current logged-in Windows user.

Tatting answered 17/8, 2015 at 18:4 Comment(2)
While this code may answer the question, it would be better to include some context, explain how it works, and describe when to use it. Code-only answers are not useful in the long run.Tonality
System.Security.Principal.WindowsIdentity.GetCurrent().Name returns the current user logged into Windows, the OP is asking for the user currently logged into the web site.Fetial
B
4

For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.

Barrio answered 13/9, 2011 at 19:10 Comment(0)
O
4

If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.

MembershipUser u = Membership.GetUser(LoginUser.UserName);
Organist answered 10/11, 2011 at 13:44 Comment(0)
V
3
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");
Varico answered 26/4, 2011 at 13:0 Comment(0)
C
3

You can use following code:

Request.LogonUserIdentity.Name;
Cunnilingus answered 14/8, 2017 at 11:42 Comment(1)
This gets you the username of the AppPool that the application is running as.Left
K
2
var ticket = FormsAuthentication.Decrypt(
                    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

if (ticket.Expired)
{
    throw new InvalidOperationException("Ticket expired.");
}

IPrincipal user =  (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
Kamakura answered 24/6, 2015 at 7:47 Comment(0)
B
2

If you happen to be working in Active Directory on an intranet, here are some tips:

(Windows Server 2012)

Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.

How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:

// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
    var userContext = System.Web.HttpContext.Current.User.Identity;
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
                                                ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
    adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...

You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:

using (HostingEnvironment.Impersonate()){ ... }

You must also have impersonate set to true in your web.config:

<system.web>
    <identity impersonate="true" />

You must have Windows authentication on in web.config:

<authentication mode="Windows" />
Burrow answered 22/1, 2016 at 16:19 Comment(4)
I do not believe so, as this is explicitly using your Active Directory user credentials. Why would you have 'Forms' if you desire your users to be authenticated via AD?Delinda
In our organization, there are locations where we have a couple of workstations that are shared by several "field" personnel. Because of that, we are required to add the login page to our intranet web applications.Garamond
as a workaround: you could have two copies of this app running, one in 'Forms' mode with it's own identity tables or you can mix both in one app, but it's trickier. A quick google revealed this: #2251421Delinda
<identity impersonate="true" /> might need to change if mixingDelinda
H
2

In Asp.net Mvc Identity 2,You can get the current user name by:

var username = System.Web.HttpContext.Current.User.Identity.Name;
Haematocele answered 29/9, 2017 at 14:18 Comment(0)
K
2

If any one still reading this then, to access in cshtml file I used in following way.

<li>Hello @User.Identity.Name</li>
Kakemono answered 24/10, 2020 at 14:56 Comment(0)
E
1

In the IIS Manager, under Authentication, disable: 1) Anonymous Authentication 2) Forms Authentication

Then add the following to your controller, to handle testing versus server deployment:

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;
Extend answered 1/5, 2019 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.