Get Current User Identity - potatoscript/asp.net.core.mvc GitHub Wiki

  1. From the Controller base class, you can get the IClaimsPrincipal from the user property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
  1. Check the claims without a round trip to the database
bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); //Get user id
  1. Other fields can be fetched from the database's User entity
  • Get the user manager using dependency injection
private UserManager<ApplicationUser> _userManager;
//class constructor
public MyController(userManager<ApplicationUser> userManager)
{
   _userManager = userManager;
}
  • And use it
   var user = await _userManager.GetUserAsync(User);
   var email = user.Email;
   // The await operator suspends evaluation of the enclosing async method until the
   // asynchronous operation represented by its operand completes.
   // When the asynchronous operation completes, the await operator returns the result of the operation, if any.