If your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
From the Controller
base class, you can get the ClaimsPrincipal
from the User
property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
You can check the claims directly (without a round trip to the database):
bool isAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
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;
If your code is a service class, you can use dependency injection to get an IHttpContextAccessor
that lets you get the User
from the HttpContext.
private IHttpContextAccessor _httpContextAccessor;
public MyClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private void DoSomething()
{
var user = _httpContextAccessor.Context?.User;
}