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;.
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).
Set*_* IK 12
万一你和我一样,用户实体的Id字段是一个Int或除字符串以外的其他东西,
using Microsoft.AspNet.Identity;
int userId = User.Identity.GetUserId<int>();
Run Code Online (Sandbox Code Playgroud)
会做的
我使用 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)
我遇到过同样的问题。我目前正在使用 Asp.net Core 2.2。我用下面的一段代码解决了这个问题。
using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
Run Code Online (Sandbox Code Playgroud)
我希望这对某人有用。
| 归档时间: |
|
| 查看次数: |
98014 次 |
| 最近记录: |