我正在尝试在 ASP.NET Core 2.1 MVC 项目中获取用户 ID.
I'm trying to get the user id in an ASP.NET Core 2.1 MVC project.
但是,我只能收到电子邮件.我几乎可以肯定必须有 1/2 行的方式来获取它(在 ASP.NET MVC 成员资格中它只是 var loggingInUserId = User.Identity.GetUserId();
However, I was only able to get the email. I'm almost sure there has to be a 1/2 line way to get it (in the ASP.NET MVC membership it was just var loggedInUserId = User.Identity.GetUserId();
到目前为止我是这样尝试的:
I tried so far like this:
var loggedInUserId = User.Identity.ToString(); // Result = Name (E-mail) // var loggedInUserId = User.Identity.Name; // Result (E-mail)&这就是我现在需要的
& this is now what I need
推荐答案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 的实例(或者想要注入一个),那么你可以使用 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); }更多推荐
在 ASP.NET Core 2 中获取用户 ID
发布评论