Hello, I would like to know how can I get currently logged in User ID using ASP.NET Core Identity in ASP.NET Core 3 or 6? Trying to Use MVC Version 'User.Identity.GetUserId()
' but it doesn't help.
If you are using .NET Core 6 or above, trying using below code for getting
UserId
, in Controller
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
OR
If above code doesn't work and you are using ASP.NET Core 2 or above, you can simply use below code to get
UserId
in Controller as below
public class HomeController: Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId
// to get current user info
var user = await _userManager.FindByIdAsync(userId);
// to give the user's userName
var userName = User.FindFirstValue(ClaimTypes.Name)
// For ASP.NET Core <= 3.1
ApplicationUser applicationUser = await _userManager.GetUserAsync(User);
string userEmail = applicationUser?.Email; // will give the user's Email
// For ASP.NET Core >= 5.0
var userEmail = User.FindFirstValue(ClaimTypes.Email) // will give the user's Email
}
}
@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{
string userId = _userManager.GetUserId(User);
}
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value
@inject SignInManager<User> SignInManager
@if (SignInManager.IsSignedIn(User))
{
<div> User logged in</div>
}
That should work.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly