[c#] How to get the current user in ASP.NET MVC

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?

This question is related to c# .net asp.net-mvc iis forms-authentication

The answer is


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

This will get the current logged-in Windows user.


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

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

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;

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;

I use:

Membership.GetUser().UserName

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


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

You can use following code:

Request.LogonUserIdentity.Name;

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

You can use following code:

Request.LogonUserIdentity.Name;

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;

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

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

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

I use:

Membership.GetUser().UserName

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


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

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

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'

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

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

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


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

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

You just need User.Identity.Name.


I use:

Membership.GetUser().UserName

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


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


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

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

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

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


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'

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


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


I use:

Membership.GetUser().UserName

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


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


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

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;

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

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

This will get the current logged-in Windows user.


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


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


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

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

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


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.

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

You just need User.Identity.Name.


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

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to iis

ASP.NET Core 1.0 on IIS error 502.5 CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Publish to IIS, setting Environment Variable IIS Manager in Windows 10 The page cannot be displayed because an internal server error has occurred on server The service cannot accept control messages at this time NuGet: 'X' already has a dependency defined for 'Y' Changing project port number in Visual Studio 2013 System.Data.SqlClient.SqlException: Login failed for user "This operation requires IIS integrated pipeline mode."

Examples related to forms-authentication

How to get the cookie value in asp.net website How to check user is "logged in"? ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired ASP.NET MVC - Set custom IIdentity or IPrincipal Why is <deny users="?" /> included in the following example? FormsAuthentication.SignOut() does not log the user out How to get the current user in ASP.NET MVC