How to get the current user in ASP.NET MVC
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
.
ASP.NET MVC 5 - Identity. How to get current ApplicationUser
You should not need to query the database directly for the current ApplicationUser.
That introduces a new dependency of having an extra context for starters, but going forward the user database tables change (3 times in the past 2 years) but the API is consistent. For example the users
table is now called AspNetUsers
in Identity Framework, and the names of several primary key fields kept changing, so the code in several answers will no longer work as-is.
Another problem is that the underlying OWIN access to the database will use a separate context, so changes from separate SQL access can produce invalid results (e.g. not seeing changes made to the database). Again the solution is to work with the supplied API and not try to work-around it.
The correct way to access the current user object in ASP.Net identity (as at this date) is:
var user = UserManager.FindById(User.Identity.GetUserId());
or, if you have an async action, something like:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
FindById
requires you have the following using statement so that the non-async UserManager
methods are available (they are extension methods for UserManager, so if you do not include this you will only see FindByIdAsync
):
using Microsoft.AspNet.Identity;
If you are not in a controller at all (e.g. you are using IOC injection), then the user id is retrieved in full from:
System.Web.HttpContext.Current.User.Identity.GetUserId();
If you are not in the standard Account controller you will need to add the following (as an example) to your controller:
1. Add these two properties:
/// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }
/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
2. Add this in the Controller's constructor:
this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
Update March 2015
Note: The most recent update to Identity framework changes one of the underlying classes used for authentication. You can now access it from the Owin Context of the current HttpContent.
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
Addendum:
When using EF and Identity Framework with Azure, over a remote database connection (e.g. local host testing to Azure database), you can randomly hit the dreaded “error: 19 - Physical connection is not usable”. As the cause is buried away inside Identity Framework, where you cannot add retries (or what appears to be a missing .Include(x->someTable)
), you need to implement a custom SqlAzureExecutionStrategy
in your project.
ASP.NET MVC: Get user id of currently logged in user
Solved the problem by following this link: howto get the user id from a FormsAuthentication page in asp.net MVC? posted by https://stackoverflow.com/users/2516718/derloopkat
The System.Web.HttpContext.Current.User.Identity.Name
Function returns the "name" attribute in the Authentication Ticket, which in my case was the email address. I then got the User ID by having a query to the Users database.
db.Users.Where(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).FirstOrDefault().ID;
Thanks for everybody's help.
Update in 2020: The query can be simplified to:
db.Users.FirstOrDefault(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).ID;
How to get current user, and how to use User class in MVC5?
If you're coding in an ASP.NET MVC Controller, use
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
Worth mentioning that User.Identity.IsAuthenticated
and User.Identity.Name
will work without adding the above mentioned using
statement. But GetUserId()
won't be present without it.
If you're in a class other than a Controller, use
HttpContext.Current.User.Identity.GetUserId();
In the default template of MVC 5, user ID is a GUID stored as a string.
No best practice yet, but found some valuable info on extending the user profile:
- Overview of
Identity
: https://devblogs.microsoft.com/aspnet/introducing-asp-net-identity-a-membership-system-for-asp-net-applications/ - Example solution regarding how to extend the user profile by adding an extra property: https://github.com/rustd/AspnetIdentitySample
Related Topics
Windows 10 Universal App File/Directory Access
Draw Semi Transparent Overlay Image All Over the Windows Form Having Some Controls
How to Get JSON.Net to Serialize Members of a Class Deriving from List<T>
C# Equivalent of SQL Server Datatypes
Using C# to Check If String Contains a String in String Array
Why Can't I Use the 'Await' Operator Within the Body of a Lock Statement
How to Check If a Type Is a Subtype or the Type of an Object
Update Row If It Exists Else Insert Logic with Entity Framework
How to Get a List of Users from Active Directory
Selectsinglenode Returns Null When Tag Contains Xmlnamespace
Select Right Generic Method with Reflection
Reference Assemblies for Framework ".Netframework,Version=V4.7.1" Were Not Found