How to get Currently logged in UserId in ASP.NET Core?


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.


Asked by:- jaya
0
: 4347 At:- 10/4/2022 3:10:17 PM
ASP.NET Core Get UserId







1 Answers
profileImage Answered by:- vikas_jk

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
    }
}

To Get UserId in View in ASP.NET Core

@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ 
   string userId = _userManager.GetUserId(User); 
}

In APIController

var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value

To check if user is logged in, within a View in ASP.NET Core:

@inject SignInManager<User> SignInManager

@if (SignInManager.IsSignedIn(User))
{
  <div> User logged in</div>
}

That should work.

1
At:- 10/4/2022 3:19:30 PM
Thanks for correct answer, I was able to get userId. 0
By : jaya - at :- 10/4/2022 3:26:09 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use