Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ID of the current user ASP.NET Membership

How do you guys manage to get the ID of the current user using the ASP.NET Membership Provider? My application is an MVC 3 using Database First approach, so I created my own database and the Membership Provider and Role Provider are using my tables (Custom Membership and Role Provider).

In one of my page (feedback), user can send feedback about my website and if he's connected, I want to include the UserID in the table when I insert.

But since the ASP.NET Membership is an IIdentity, the only thing I can access is the Name. I don't want to create a link between 2 tables using the name, I want the ID!

So what do you do in your application for this VERY simple task? I mean, in almost every page where a connected user needs to insert a value, we need the ID of the user to create the correct foreign key to the user table, right? By the way, I'm very new to this MVC framework, before that I was using ASP.NET aspx and for the user information, I was using the Session which gave me the current ID, Name and other fields as needed. Since this implementation using the Session object gave me trouble in shared hosting, I want to use the real membership.

Thanks!

EDIT

The ID I want must be an integer (in fact, I want the UserID field that is in the User table).

like image 553
Jean-François Côté Avatar asked Oct 31 '12 13:10

Jean-François Côté


People also ask

How can get current user details in ASP.NET core?

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

What is HttpContext user?

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.

How does membership GetUser work?

GetUser() retrieves the user information from the data source and creates a MembershipUser object populated with the returned data. If you use one of the GetUser overloads that does not take a username parameter, GetUser returns the information for the current logged-on membership user.

How does ASP Net membership work?

The ASP.NET membership provider is a feature that enables ASP.NET developers to create Web sites that allow users to create unique user name and password combinations. With this facility, any user can establish an account with the site, and sign in for exclusive access to the site and its services.


1 Answers

Try this;

MembershipUser mu = Membership.GetUser("username");
string userId = mu.ProviderUserKey.ToString();

For currently logged in user you could use without passing the username;

string userId = Membership.GetUser().ProviderUserKey.ToString();
like image 113
Kaf Avatar answered Oct 22 '22 11:10

Kaf