Get current user id in ASP.NET Identity 2.0 Get current user id in ASP.NET Identity 2.0 asp.net asp.net

Get current user id in ASP.NET Identity 2.0


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


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


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