Get current logged in user's identifier with ASP.NET Core Identity

To get some data about the current logged in user, you have to call the service Microsoft.AspNetCore.Identity.UserManager<T>, which implements all the methods you need.

A good practice is to add a private method in your controller, calling this service.

public class AccountController : Controller
    private readonly UserManager<ApplicationUser> _userManager;
    public AccountController(UserManager<ApplicationUser> userManager)
		_userManager = userManager;
	public async Task<string> GetCurrentUserId()
		ApplicationUser usr = await GetCurrentUserAsync();
		return usr?.Id;

    private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
  • ASP.NET Core
  • Identity