C# 在ASP.NET Identity 2.0中获取当前用户id

C# 在ASP.NET Identity 2.0中获取当前用户id,c#,asp.net,asp.net-identity,C#,Asp.net,Asp.net Identity,我刚刚切换到使用Identity Framework的新2.0版本。在1.0中,我可以使用manager.FindByIdAsync(user.Identity.GetUserId())获取用户对象。GetUserId()方法在2.0中似乎不存在 现在我所能做的就是使用manager.findbyemailsync(User.Identity.Name),它引用users表中的username字段。在我的应用程序中,此字段设置为与电子邮件字段相同 我可以看到,当有人需要更新他们的电子邮件时,这会

我刚刚切换到使用Identity Framework的新2.0版本。在1.0中,我可以使用
manager.FindByIdAsync(user.Identity.GetUserId())
获取用户对象。
GetUserId()
方法在2.0中似乎不存在

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


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

GetUserId()
IIdentity
上的扩展方法,它位于
Microsoft.AspNet.Identity.IdentityExtensions
中。确保已使用Microsoft.AspNet.Identity添加带有
的命名空间
为了在Asp.net Identity 2.0中获取当前用户ID,首先导入
Microsoft.AspNet.Identity

C#:

using Microsoft.AspNet.Identity;
Imports Microsoft.AspNet.Identity
VB.NET:

using Microsoft.AspNet.Identity;
Imports Microsoft.AspNet.Identity

然后调用
User.Identity.GetUserId()
任意位置:

strCurrentUserId = User.Identity.GetUserId()

此方法返回当前用户id,作为数据库中用户id的定义数据类型(默认值为
String
)。

以防您像我一样,并且用户实体的id字段是Int或字符串以外的其他内容

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();
使用Microsoft.AspNet.Identity;
int userId=User.Identity.GetUserId();

我也有同样的问题。我目前正在使用Asp.net Core 2.2。我用下面的代码解决了这个问题

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

我希望这对某人有用。

另请参见:这似乎不适用于Identity 2。任何建议都会留在那里。我现在正在Identity 2项目中使用GetUserId()。在Identity 3.0中,这看起来已移动到System.Security.Principal命名空间。是否有任何方法获取当前用户角色?我应该什么时候设定角色?注意:我正在使用自定义存储提供程序..您是如何获得用户ID的,请告诉我,我遇到了相同的问题。您能告诉我在哪里可以找到Microsoft.AspNet.Identity命名空间的相应DLL吗?您救了我一命