Getting Current User Id

LunchMarble picture LunchMarble · May 10, 2012 · Viewed 11k times · Source

I am trying to get the currently logged in user's UserId as mentioned in this post http://msdn.microsoft.com/en-us/library/aa478949.aspx as part of the aspnet_Membership table.

Here's where I am looking:

    MembershipUser user = null;

    if (User != null && User.Identity != null && !string.IsNullOrEmpty(User.Identity.Name))
    {
        user = Membership.GetUser(User.Identity.Name);
    }

    if (user != null)
    {
        //int id = user.UserId;
    }

MembershipUser does not have a UserId. I am trying to user the UserId as a foreign key for other tables I will create. I can use the UserName, but I figured it may be better to use the UserId.

Answer

Mark Hall picture Mark Hall · May 10, 2012

Try and see if the MembershipUser.ProvideUserKey Property works for you

From above link:

The ProviderUserKey property exposes the identifier from the membership data source typed as object. The type of the identifier depends on the MembershipProvider or the MembershipUser. In the case of the SqlMembershipProvider, the ProviderUserKey can be cast as a Guid, since the SqlMembershipProvider stores the user identifier as a UniqueIdentifier.