在 ASP.NET Identity 2.0中获取当前用户 ID

我刚刚转向使用新的身份框架2.0版本。在1.0中,我可以通过使用 manager.FindByIdAsync(User.Identity.GetUserId())获得一个用户对象。GetUserId()方法在2.0中似乎不存在。

现在我能想到的就是使用 manager.FindByEmailAsync(User.Identity.Name),它引用 users 表中的 username 字段。在我的应用程序中,这被设置为与电子邮件字段相同。

当有人需要更新他们的电子邮件时,我可以看到这会引起问题。在 Identity 2.0框架中,有没有一种基于不变值 (比如 id 字段)获取当前登录的用户对象的方法?

137149 次浏览

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

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.

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