Get user id in ASP.NET Core 2

本秂侑毒 提交于 2019-12-23 13:07:53

问题


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 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


回答1:


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<TUser> (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);
    }
    



回答2:


You need to inject dependency in the controller like shown below:

[Authorize]
public class AccountController: Controller
{
private readonly UserManager<IdentityUser> _userManager;

    public AccountController(UserManager<IdentityUser> userManager) 
    {
        _userManager = userManager;
    }
}

Now, you can use below code anywhere inside that controller to get user details.

var user = await _userManager.FindByEmailAsync(model.EmailID);

Now, You can use user.Id to get userId.




回答3:


In Asp.net Core 2.2, I solved this problem with the following piece of code.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

This way you will get the user information by his email. User.Identity.Name will provide you the email address of the current logged in user.

I hope this will be useful to someone.



来源:https://stackoverflow.com/questions/51765214/get-user-id-in-asp-net-core-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!