Get user id in ASP.NET Core 2

前端 未结 3 632
慢半拍i
慢半拍i 2021-01-12 03:19

I\'m trying to get the user id in an ASP.NET Core 2.1 MVC project.

However, I was only able to get the email. I\'m almost sure there has to be a 1/2 line way to get

3条回答
  •  梦谈多话
    2021-01-12 03:52

    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:

    1. The first and easiest is just pull out the claim:

      var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
      
    2. If you already have an instance of UserManager (or want to inject one), then you can use the GetUserId() method on that:

      var userId = _userManager.GetUserId(User);
      
    3. 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);
      }
      

提交回复
热议问题