Question

How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project?

Can UserId be included in Profile namespace next to UserName (System.Web.Profile.ProfileBase)?

Was it helpful?

Solution 3

I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago.

My original question was about UserId and it is not available from:

System.Web.HttpContext.Current.User.Identity.Name

OTHER TIPS

Try this:

MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
Response.Write("CurrentUser ID :: " + CurrentUser.ProviderUserKey);

Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache.

If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId.

If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider.

EDIT:

See ScottGu's article on providers which provides a link to downloading the actual source code for i.e. SqlMembershipProvider.

But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it.

For something more to consider (but be very careful because of cookie size restrictions): Forms Auth: Membership, Roles and Profile with no Providers and no Session

Try the following:

Membership.GetUser().ProviderUserKey
public string GetUserID()
            {
                MembershipUser _User;
                string _UserId = "";
                _User = Membership.GetUser();
                Guid UserId = (Guid)_User.ProviderUserKey;
                return _UserId = UserId.ToString();
            }

You have two options here:

1) Use username as the primary key for your user data table i.e:

select * from [dbo.User] where Username = 'andrew.myhre'

2) Add UserID to the profile.

There are pros and cons to each method. Personally I prefer the first, because it means I don't necessarily need to set up the out-of-the-box profile provider, and I prefer to enforce unique usernames in my systems anyway.

Andrew: I'd be careful of doing a query like what you've shown as by default, there's no index that matches with that so you run the risk of a full table scan. Moreover, if you're using your users database for more than one application, you haven't included the application id.

The closest index is aspnet_Users_Index which requires the ApplicationId and LoweredUserName.

EDIT:

Oops - reread Andrew's post and he's not doing a select * on the aspnet_Users table, but rather, a custom profile/user table using the username as the primary key.

I had this problem, the solution is in the web.config configuration, try configuring web.config with these:

 <roleManager
             enabled="true"
             cacheRolesInCookie="true"
             defaultProvider="QuickStartRoleManagerSqlProvider"
             cookieName=".ASPXROLES"
             cookiePath="/"
             cookieTimeout="30"
             cookieRequireSSL="false"
             cookieSlidingExpiration="true"
             createPersistentCookie="false"
             cookieProtection="All">
  <providers>
    <add name="QuickStartRoleManagerSqlProvider"
        type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        connectionStringName="ASPNETDB"
        applicationName="SecurityQuickStart"/>
  </providers>
</roleManager>
{
MembershipUser m = Membership.GetUser();
Response.Write("ID: " + m.ProviderUserKey.ToString());
}

Will give you the UserID (uniqueidentifier) for the current user from the aspnet_Membership table - providing the current has successfully logged in. If you try to <%= %> or assign that value before a successful authentication you will get the error "Object reference not set to an instance of an object".

http://www.tek-tips.com/viewthread.cfm?qid=1169200&page=1

Have you tried using System.Web.HttpContext.Current.User.Identity.Name? (Make sure to verify that User and Identity are non-null first.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top