更新时间:2023-02-12 20:21:57
User.Identity.GetUserId()
的旧方法不再存在,但可以将ID作为对您的委托人即User
的要求.您可以通过多种方式进行操作:
The old method of User.Identity.GetUserId()
no longer exists, but the id is available as a claim on your principal, i.e. User
. There's a number of ways you can get to it:
第一个也是最简单的方法就是提出声明:
The first and easiest is just pull out the claim:
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
如果您已经有一个UserManager<TUser>
实例(或想要注入一个实例),则可以在该实例上使用GetUserId()
方法:
If you already have an instance of UserManager<TUser>
(or want to inject one), then you can use the GetUserId()
method on that:
var userId = _userManager.GetUserId(User);
最后,如果您想使用旧的方法,就像将扩展名添加到ClaimsPrincipal
并利用上面的第一种方法一样简单:
Finally, if you want the old way back, it's as simple as adding an extension to ClaimsPrincipal
and utilize the first method above:
public static class ClaimsPrincipalExtensions
{
public static string GetUserId(this ClaimsPrincipal principal) =>
principal.FindFirstValue(ClaimTypes.NameIdentifier);
}