Get user id in ASP.NET Core 2

前端 未结 3 625
慢半拍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:49

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

    [Authorize]
    public class AccountController: Controller
    {
    private readonly UserManager _userManager;
    
        public AccountController(UserManager 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.

提交回复
热议问题