[c#] ASP.NET MVC 5 - Identity. How to get current ApplicationUser

I have an Article entity in my project which has the ApplicationUser property named Author. How can I get the full object of currently logged ApplicationUser? While creating a new article, I have to set the Author property in Article to the current ApplicationUser.

In the old Membership mechanism it was simple, but in the new Identity approach I don't know how to do this.

I tried to do it this way:

  • Add using statement for Identity extensions: using Microsoft.AspNet.Identity;
  • Then I try to get the current user: ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == User.Identity.GetUserId());

But I get the following exception:

LINQ to Entities does not recognize the method 'System.String GetUserId(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression. Source=EntityFramework

This question is related to c# asp.net-mvc-5 identity asp.net-identity

The answer is


The code of Ellbar works! You need only add using.

1 - using Microsoft.AspNet.Identity;

And... the code of Ellbar:

2 - string currentUserId = User.Identity.GetUserId(); ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

With this code (in currentUser), you work the general data of the connected user, if you want extra data... see this link


In case someone is working with Identity users in web forms, I got it working by doing so:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindById(User.Identity.GetUserId());

For MVC 5 just look inside the EnableTwoFactorAuthentication method of ManageController in WebApplication template scaffold, its being done there:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> EnableTwoFactorAuthentication()
        {
            await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
            if (user != null)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
            }
            return RedirectToAction("Index", "Manage");
        }

The answer is right there as suggested by Microsoft itself:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

It will have all the additional properties you defined in ApplicationUser class.


Right now the asp.mvc project template creates an account controller that gets the usermanager this way:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()

The following works for me:

ApplicationUser user = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());

As of ASP.NET Identity 3.0.0, This has been refactored into

//returns the userid claim value if present, otherwise returns null
User.GetUserId();

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;


string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

I was successfully available to get Application User By Following Piece of Code

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = manager.FindById(User.Identity.GetUserId());
            ApplicationUser EmpUser = user;

Its in the comments of the answers but nobody has posted this as the actual solution.

You just need to add a using statement at the top:

using Microsoft.AspNet.Identity;

ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser currentUser = UserManager.FindById(User.Identity.GetUserId());

string ID = currentUser.Id;
string Email = currentUser.Email;
string Username = currentUser.UserName;

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 asp.net-mvc-5

'router-outlet' is not a known element The type or namespace name 'System' could not be found How to get 'System.Web.Http, Version=5.2.3.0? EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType How to extend available properties of User.Identity How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 How to get JSON object from Razor Model object in javascript The model backing the 'ApplicationDbContext' context has changed since the database was created How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project? MVC 5 Access Claims Identity User Data

Examples related to identity

Firebase: how to generate a unique numeric ID for key? ASP.NET MVC 5 - Identity. How to get current ApplicationUser SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry Auto increment primary key in SQL Server Management Studio 2012 What is the difference between == and equals() in Java? SQL Server, How to set auto increment after creating a table without data loss? Where is the Microsoft.IdentityModel dll What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()? Why does comparing strings using either '==' or 'is' sometimes produce a different result? Handling identity columns in an "Insert Into TABLE Values()" statement?

Examples related to asp.net-identity

ASP.NET Core Identity - get current user How to get current user in asp.net core Adding ASP.NET MVC5 Identity Authentication to an existing project How to get the current logged in user Id in ASP.NET Core How to extend available properties of User.Identity Get current user id in ASP.NET Identity 2.0 Get the current user, within an ApiController action, without passing the userID as a parameter ASP.NET Identity - HttpContext has no extension method for GetOwinContext ASP.NET MVC 5 - Identity. How to get current ApplicationUser OWIN Security - How to Implement OAuth2 Refresh Tokens