Get logged in user's id

35,976

Solution 1

I think you're looking for ProviderUserKey - Gets the user identifier from the membership data source for the user.

object id = Membership.GetUser().ProviderUserKey

Membership.GetUser() - Gets the information from the data source and updates the last-activity date/time stamp for the current logged-on membership user.

Solution 2

Try this:

using Microsoft.AspNet.Identity;
User.Identity.GetUserId();

That's how its done in the partial views for current MVC (MVC5/EF6/VS2013) templates.

Correct me if I'm wrong, because I've seen Aviatrix's answers a lot, but what happens if more than one user has the same name in the database?

Solution 3

The best way to do so is to use the WebSecurty class

var memberId = WebSecurity.GetUserId(User.Identity.Name);

and don't forget to add [InitializeSimpleMembership] on top of your controller :)

Share:
35,976

Related videos on Youtube

naveed
Author by

naveed

Updated on July 19, 2020

Comments

  • naveed
    naveed almost 4 years

    How can I get the logged in user's UserId? I'm using the standard system generated AccountModel. I can get the username using:

    User.Identity.Name
    

    but I don't see the UserId field. I want to use the UserId as a foreign key for another table.

    • AJ.
      AJ. over 11 years
      Simple Membership? ASP.NET Membership?
  • naveed
    naveed over 11 years
    Hmm, I'm getting: Error 1 'System.Web.Security.MembershipUser' does not contain a definition for 'GetUser'
  • Erik Philips
    Erik Philips over 11 years
    Thanks, typo there, it was suppose to be Membership.
  • Erik Philips
    Erik Philips almost 11 years
    As long as your provider follows the requirements to use an int as the Unique Identifier.
  • Marcello Grechi Lins
    Marcello Grechi Lins over 9 years
    Membership.GetUser().UserName for the username instead of the internal membership database key
  • usefulBee
    usefulBee over 7 years
    This solution is not possible if the user is already logged in and trying to change the current password.