Get user id in ASP.NET Core 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.
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);
If you already have an instance of
UserManager<TUser>
(or want to inject one), then you can use theGetUserId()
method on that:var userId = _userManager.GetUserId(User);
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); }