previously I was using AspNet Microsoft.AspNet.Identity; to get the current user ID accessing api with following code
Code
string userId = User.Identity.GetUserId();Now I migrated whole project from AspNet to AspNetCore but how can I get current user ID accessing api?
Tried following code which returned username
Code
var userName = User.FindFirstValue(ClaimTypes.Name);I googled and found I have to use the following code to get userID,
Code
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);but it returned with 204, No Content

Amit MohantyRank #112 · 20K reputationPosted Jun 9, 2022, 12:16 AM EDT
Sachin SinghRank #66 · 26.2K reputationPosted Jun 9, 2022, 4:31 AM EDT
John Davis48 reputationPosted Jun 9, 2022, 10:37 AM EDT
@Sachin Singh , I Finally found a solution with your suggested code
var user = await _userManager.FindByNameAsync(User.Identity.Name); var userId = user?.Id;John Davis48 reputationPosted Jun 9, 2022, 4:34 AM EDT
@Sachin Singh Thank you, but it returns me
Sachin SinghRank #66 · 26.2K reputationPosted Jun 9, 2022, 6:34 AM EDT
John Davis48 reputationPosted Jun 9, 2022, 10:10 AM EDT
@Sachin Singh Can you please explain? my project is an Rest api project cloned from
https://www.c-sharpcorner.com/article/jwt-authentication-with-refresh-tokens-in-net-6-0/
John Davis48 reputationPosted Jun 9, 2022, 11:02 AM EDT