获取ASP.NET Identity 2.0中的当前用户标识

jas*_*ley 73 c# asp.net asp.net-identity

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

现在我可以弄清楚的是使用manager.FindByEmailAsync(User.Identity.Name)哪些引用users表中的用户名字段.在我的应用程序中,它设置为与电子邮件字段相同.

当有人需要更新他们的电子邮件时,我可以看到这会导致问题.有没有办法根据Identity 2.0 Framework中不变的值(例如id字段)获取当前登录的用户对象?

Ant*_*Chu 96

GetUserId()是一个扩展方法IIdentity,它在Microsoft.AspNet.Identity.IdentityExtensions.确保已添加命名空间using Microsoft.AspNet.Identity;.

  • 在Identity 3.0中,这看起来已移至System.Security.Principal命名空间. (4认同)
  • 这似乎不适用于Identity2。请提出任何建议 (2认同)
  • 还应该在那里.我现在正在我的身份2项目中使用GetUserId(). (2认同)

Mos*_*taf 54

为了在Asp.net Identity 2.0中获取CurrentUserId,首先导入Microsoft.AspNet.Identity:

C#:

using Microsoft.AspNet.Identity;
Run Code Online (Sandbox Code Playgroud)

VB.NET:

Imports Microsoft.AspNet.Identity
Run Code Online (Sandbox Code Playgroud)


然后呼叫User.Identity.GetUserId()你想要的任何地方:

strCurrentUserId = User.Identity.GetUserId()
Run Code Online (Sandbox Code Playgroud)

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

  • 你能告诉我在哪里可以找到 Microsoft.AspNet.Identity 命名空间的相应 DLL 吗? (2认同)

Set*_* IK 12

万一你和我一样,用户实体的Id字段是一个Int或除字符串以外的其他东西,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();
Run Code Online (Sandbox Code Playgroud)

会做的


Nic*_*las 7

我使用 Claims 来获取登录用户的 userId、用户名和电子邮件。

            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);
Run Code Online (Sandbox Code Playgroud)


Moh*_*sin 5

我遇到过同样的问题。我目前正在使用 Asp.net Core 2.2。我用下面的一段代码解决了这个问题。

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有用。