How can I access UserId in ASP.NET Membership without using Membership.GetUser()?
Asked Answered
C

11

19

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)?

Chat answered 28/9, 2008 at 22:25 Comment(2)
Can you expand on the reason why?Haem
When I call Membership.GetUser().ProviderUserKey everytime is maked call to DB to retrieve this UserIdChat
C
4

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
Chat answered 2/10, 2008 at 8:10 Comment(1)
Following up on your post, if you import using Microsoft.AspNet.Identity; you will have access to User.Identity.GetUserId()Bimah
T
26

Try this:

MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
Response.Write("CurrentUser ID :: " + CurrentUser.ProviderUserKey);
Tavie answered 6/1, 2009 at 14:27 Comment(1)
Passing in the username certainly helps, as otherwise I was getting null back! Thanks for this.Wellchosen
V
13

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

Version answered 29/9, 2008 at 5:50 Comment(1)
Nice little article at the end of your answer.Zakaria
C
4

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
Chat answered 2/10, 2008 at 8:10 Comment(1)
Following up on your post, if you import using Microsoft.AspNet.Identity; you will have access to User.Identity.GetUserId()Bimah
B
2

Try the following:

Membership.GetUser().ProviderUserKey
Boardinghouse answered 15/4, 2013 at 23:40 Comment(0)
C
1
public string GetUserID()
            {
                MembershipUser _User;
                string _UserId = "";
                _User = Membership.GetUser();
                Guid UserId = (Guid)_User.ProviderUserKey;
                return _UserId = UserId.ToString();
            }
Critter answered 21/11, 2014 at 21:38 Comment(0)
L
0

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.

Lennalennard answered 29/9, 2008 at 9:4 Comment(0)
V
0

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.

Version answered 30/9, 2008 at 17:49 Comment(0)
C
0

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

Conundrum answered 30/9, 2008 at 18:17 Comment(0)
G
0
{
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

Gavotte answered 7/12, 2008 at 3:29 Comment(0)
G
0

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>
Geriatrics answered 13/7, 2011 at 9:49 Comment(0)
E
0

internally it's executing below script in sql server

select * from vw_aspnet_MembershipUsers where USERNAME like '%username%'
Ectoderm answered 29/7, 2022 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.