How to get the current user in ASP.NET MVC

C#.Netasp.net MvcIisForms Authentication

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

System.Web.HttpContext.Current.User.Identity.Name

Solution 5 - C#

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.

Solution 6 - C#

I use:

Membership.GetUser().UserName

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

Solution 7 - C#

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

Solution 8 - C#

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();

Solution 9 - C#

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;

Solution 10 - C#

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'

Solution 11 - C#

This page could be what you looking for:
https://stackoverflow.com/questions/4613992/using-page-user-identity-name-in-mvc3

You just need User.Identity.Name.

Solution 12 - C#

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

This will get the current logged-in Windows user.

Solution 13 - C#

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

Solution 14 - C#

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);

Solution 15 - C#

You can use following code:

Request.LogonUserIdentity.Name;

Solution 16 - C#

IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
		...
                   currentUser.IsInRole("Operator");

Solution 17 - C#

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));

Solution 18 - C#

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" />

Solution 19 - C#

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

var username = System.Web.HttpContext.Current.User.Identity.Name;

Solution 20 - C#

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;

Solution 21 - C#

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

<li>Hello @User.Identity.Name</li>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSerhat OzgelView Question on Stackoverflow
Solution 1 - C#HaackedView Answer on Stackoverflow
Solution 2 - C#PieterView Answer on Stackoverflow
Solution 3 - C#doveView Answer on Stackoverflow
Solution 4 - C#radbyxView Answer on Stackoverflow
Solution 5 - C#jrbView Answer on Stackoverflow
Solution 6 - C#SeanView Answer on Stackoverflow
Solution 7 - C#tifozView Answer on Stackoverflow
Solution 8 - C#Gilberto B. Terra Jr.View Answer on Stackoverflow
Solution 9 - C#MattCView Answer on Stackoverflow
Solution 10 - C#Raj BaralView Answer on Stackoverflow
Solution 11 - C#heriawanView Answer on Stackoverflow
Solution 12 - C#Clay SmithView Answer on Stackoverflow
Solution 13 - C#PieterView Answer on Stackoverflow
Solution 14 - C#live-loveView Answer on Stackoverflow
Solution 15 - C#Rajeev JayaswalView Answer on Stackoverflow
Solution 16 - C#Gediminas BukauskasView Answer on Stackoverflow
Solution 17 - C#Ognyan DimitrovView Answer on Stackoverflow
Solution 18 - C#Beau D'AmoreView Answer on Stackoverflow
Solution 19 - C#Fereydoon BarikzehyView Answer on Stackoverflow
Solution 20 - C#Daniel KingView Answer on Stackoverflow
Solution 21 - C#SamifView Answer on Stackoverflow