Get current user id in ASP.NET Identity 2.0

C#asp.netasp.net Identity

C# Problem Overview


I just switched over to using the new 2.0 version of the Identity Framework. In 1.0 I could get a user object by using manager.FindByIdAsync(User.Identity.GetUserId()). The GetUserId() method does not seem to exists in 2.0.

Now all I can figure out is to use manager.FindByEmailAsync(User.Identity.Name) which references the username field in the users table. In my application this is set to the same as the email field.

I can see this causing issues down the road when someone needs to update their email. Is there a way to get the current logged in user object based off an unchanging value (such as the id field) in the Identity 2.0 Framework?

C# Solutions


Solution 1 - C#

GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

Solution 2 - C#

In order to get CurrentUserId in Asp.net Identity 2.0, at first import Microsoft.AspNet.Identity:

C#:

using Microsoft.AspNet.Identity;

VB.NET:

Imports Microsoft.AspNet.Identity


And then call User.Identity.GetUserId() everywhere you want:

strCurrentUserId = User.Identity.GetUserId()

This method returns current user id as defined datatype for userid in database (the default is String).

Solution 3 - C#

Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

will do the trick

Solution 4 - C#

I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

I hope this will be useful to someone.

Solution 5 - C#

I used Claims to get the userId, username and email of the logged in user.

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // will give the user's userId
        //userName = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName
        //email = User.FindFirstValue(ClaimTypes.Email);

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
QuestionjasonpresleyView Question on Stackoverflow
Solution 1 - C#Anthony ChuView Answer on Stackoverflow
Solution 2 - C#MoshtafView Answer on Stackoverflow
Solution 3 - C#Seth IKView Answer on Stackoverflow
Solution 4 - C#MohsinView Answer on Stackoverflow
Solution 5 - C#NicolasView Answer on Stackoverflow