Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current user id in ASP.NET Identity 2.0

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?

like image 915
jasonpresley Avatar asked Mar 25 '14 02:03

jasonpresley


People also ask

How to Get logged in user id in ASP net c#?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

What is HttpContext current user identity name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.


3 Answers

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

like image 89
Anthony Chu Avatar answered Oct 01 '22 20:10

Anthony Chu


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

like image 38
Moshtaf Avatar answered Oct 03 '22 20:10

Moshtaf


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

like image 16
Seth IK Avatar answered Oct 03 '22 20:10

Seth IK