Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Core Get User by User Id

Tags:

Using Asp.net Core Identity and entity framework core, how can I get an asp.net user object by it's UserId property? I know it's possible to get the current logged in user from the HttpContext.User object using:

UserManager.GetUserAsync(HttpContext.User) 

However when an admin is logged in, I want them to be able to access/modify any user's data in order to update user Emails and PhoneNumbers, which by default are part of the asp.net user object.

Ideally I'd like to be able to do something like:

var userRecord = _userManager.GetUserById(model.userId); //update user record userRecord.Email = model.Email; userRecord.PhoneNumber = model.PhoneNumber;  var newRecord = await _userManager.UpdateAsync(userRecord); 

but obvisously, the UserManager.GetUserById() method does not currently exist.

like image 520
big_water Avatar asked Dec 27 '16 19:12

big_water


People also ask

How can we get logged in user details in asp net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How to get user Role in asp net Identity?

it gives you the AspNetUserInRoles which stores UserId and RoleId. Instead you could try UserManger 's GetRoles method which will return you List<string> of roles user is assigned. But as you mentioned it will be only one role hence you can take first value from the result of GetRoles method.


2 Answers

You can use FindByIdAsync for that:

var user = await _userManager.FindByIdAsync(model.userId); 
like image 194
Kévin Chalet Avatar answered Oct 14 '22 04:10

Kévin Chalet


You can get the current user one of this ways:

// Get the current user ID from the user claims (no DB hit)     int currentUserId = int.Parse(User.FindFirst(Claims.UserId).Value); 

And then retrieve the current user entity:

// Either via DB context: var currentUser = _context.Users.FirstOrDefault(u => u.Id == currentUserId);  // or via Usermanager: var sameUser = UserManager.Users.FirstOrDefault(u => u.Id == currentUserId); 

Or just this way:

var currentUser = UserManager.Users.FirstOrDefault(u => u.UserName == User.Identity.Name); 
like image 21
Dmitry Pavlov Avatar answered Oct 14 '22 03:10

Dmitry Pavlov