Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the UserID of a User object in ASP.Net MVC?

I have some tables that have a uniqueidentifier UserID that relates to aspnet_Users.UserID. When the user submits some data for those tables, since the controller method has an [Authorize] I get a User object. I can get the username with User.Identity.Name, but how do I get the UserID to be able to establish (the ownership) relationship?

like image 471
pupeno Avatar asked May 29 '09 06:05

pupeno


People also ask

How can I get username in MVC?

to get the current user name, however if you want to see all users record then you need to get the username by using its id, you can do this operation by joining Users table on user.id key or you can use it in View by having a method that take user id as parameter and return its Name.

How do I find my user ID in net core?

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

What is HttpContext current user identity Name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.


2 Answers

It seems you cannot get it from the User object but you can get it this way:

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey; 
like image 97
pupeno Avatar answered Sep 23 '22 01:09

pupeno


Here is the solution:

Include:

using Microsoft.AspNet.Identity; 

Then use extension methods:

User.Identity.GetUserId(); 
like image 45
faisale Avatar answered Sep 21 '22 01:09

faisale