ASP.NET: MemberShip – get the UserID of the User

I’ve read that question on many message boards so I decided to post a quick blog entry about that. It’s actually very easy.

If you use the new comfortable Login Controls of ASP.NET v2, here is how you resolve the UserID of the currently logged in user:

 

        MembershipUser myObject = Membership.GetUser();
        string UserID = myObject.ProviderUserKey.ToString();

That’s all! Hope that helps..

57 comments ↓

#1 George Flicker on 04.05.06 at 1:49 pm

Oh yea, thanks. Google is your friend :)

#2 Julio on 04.05.06 at 3:48 pm

I asked on asp.net for those few lines but didn’t get an answer, until now, thanks!

#3 JC on 07.27.06 at 11:26 am

If I have this code inside a class, should I use a httpcontext ?
I am not sure when I have to use HttpContext.Current

#4 andreas.kraus on 07.27.06 at 11:33 am

In this case you don’t have to use HttpContext, Membership is globally available.

#5 crige on 08.24.06 at 3:12 am

Thank u ,Very much !

#6 Liam on 08.29.06 at 3:04 pm

Spent a long time looking for this else where. Your a star!

#7 rao on 10.04.06 at 1:06 pm

thanks it very usfull could you please give some code sample i tried to get the userid i could not

many thanks

#8 ykk on 10.26.06 at 2:08 am

Man that saved a headache! Thank you!!!

#9 omar on 01.21.07 at 11:38 am

Thank you guy!! :wink:

#10 Reinart on 02.08.07 at 12:20 pm

As simple as that. Thank you so much.

#11 Gary on 03.08.07 at 11:37 pm

When I try to use this I get:
Membership does not contain a definition for GetUser(). Am I missing something?

Thanks.

#12 Andy Mo on 05.09.07 at 2:45 am

Cheers mate! After 2 hours of google, finally a straight forward answer!

:grin:

#13 clouds on 05.23.07 at 5:00 am

Nice one! Many thanks~ :smile:

#14 Scott Farbman on 05.29.07 at 9:20 pm

Translation to VB.NET

Dim UserID As String
Dim MemUser As MembershipUser
MemUser = Membership.GetUser()
UserID = MemUser.ProviderUserKey.ToString()

#15 shazia on 05.31.07 at 7:44 am

Helpful tip out there

#16 shazia on 05.31.07 at 7:45 am

But how to get the userid when creating a user using createuserwizard of asp.net 2.0

#17 andreas.kraus on 05.31.07 at 8:05 am

Hi shazi, you can use this here:

   29       MembershipUser user = Membership.GetUser((sender as CreateUserWizard).UserName);

   30         string UserID = user.ProviderUserKey.ToString();  

hth,
Andreas

#18 Quentin on 07.19.07 at 1:23 pm

I love you – thanks.

I am definately bookmarking your blog.

#19 Islamegy on 07.21.07 at 2:21 pm

Yesssssss.. I was always think there is some way microsoft developers implemented to get user GUID.. Thanx alot

#20 Bill Kuhn - MCSE on 08.31.07 at 9:52 pm

Simplifying just a little..

Dim UserID as String

UserID = Membership.GetUser.ProviderUserKey.ToString()

And Thanks! I had been looking for an easy way to get the UserID for a long time!

#21 Trevor on 09.04.07 at 10:50 am

Hi
I get the following error when trying to get the UserID of the table [aspnet_Users].
Error: Conversion failed when converting from a character string to uniqueidentifier

Code used:
MembershipUser _user = Membership.GetUser();

DataFile.InsertParameters["commited_to_database_by_UserId"].Type = TypeCode.Empty;
DataFile.InsertParameters["commited_to_database_by_UserId"].DefaultValue = _user.ProviderUserKey.ToString();

I am using active directory as my membership provider, should this make any diffrence to the code required.

#22 andreas.kraus on 09.04.07 at 10:56 am

Hi Trevor,

ProviderUserKey is returning an object. It looks like you need a UniqueIdentifier for your code instead of a string. Try to cast it as Guid.

hth

#23 trialblazer on 10.09.07 at 3:19 pm

I’m trying to use this function Membership.GetUser() from LoggedIn event of Login Control in ASP.NET 2/C#. but it is returning null? Any clue

#24 andreas.kraus on 10.09.07 at 3:37 pm

trialblazer,

you’d have to use something like:

MembershipUser myuser = Membership.GetUser(UserName)

hth,
Andreas

#25 Petr on 10.24.07 at 12:41 am

Thanks, that’s what I have been looking for. :razz:

#26 Dusty Reagan on 10.31.07 at 1:08 am

Simple! Thanks a ton!

#27 Neil McDonald on 10.31.07 at 4:22 pm

I’ve been looking for this for a while now – thanks!

#28 Zapp on 11.21.07 at 12:45 pm

:mrgreen: Thanks a bunch! :mrgreen:

#29 suresh on 12.12.07 at 8:43 am

Thanks a lot

#30 Abbas on 01.11.08 at 12:03 pm

Thanks a lot,
This is very helpfull for me,
May Allah success you….

#31 Chuck on 01.17.08 at 10:55 pm

Thank you this helps.

#32 Chris on 01.21.08 at 7:23 am

Ok, but how would you put into an insert parameter…so when someone adds a record I know what user added it.

Do you do in a hidden field or in the asp:Parameter? And please show/write the example verbatum since I am an new asp.net user.

I tried this but didn’t work in C# 3.5
<input id=”UserID” type=”hidden” value=”" />

#33 DieBagger on 03.20.08 at 11:51 am

Thx for this hint ;)

#34 Pedro Lopes on 04.16.08 at 4:46 pm

Hello,

This piece of code is great! I

just have one HUGE problem: when I try to get the ProviderUserKey the server always returns the same key!!!

I use
“MembershipUser user = Membership.GetUser(username);”
and then
“user.ProviderUserKey.ToString();”
and the ProviderUserKey is always the same whatever user logs in… I don’t really understand why!

Any suggestions?

Thanks in advance!

#35 Nikks on 04.23.08 at 10:01 pm

I think this code works only for the currently logged in users? I mean username should be passed before getting UserID from database.
What if for some email verification purpose UserID is required before login process.

#36 andreas.kraus on 04.24.08 at 7:36 am

Pedro:
Check your Application ID settings, I think you’re running 2 different Application IDs in your Membership Environment.

Nikks:
In that case you just pass on the UserID or UserName to Membership.GetUser();.

For example:
MembershipUser myObject = Membership.GetUser(“Bill”);

#37 Josken on 05.13.08 at 11:35 pm

I have trouble when i try to register a new user while logged in with another user using the CreateUserWizard-control and then login with the new account.

Then I get

Membership.GetUser().UserName == null

Other then that UserName returns the correct login name.

Any ideas?

#38 Lulu on 05.19.08 at 1:30 pm

Thank you very much, been searching for hours for this!

ASP.NET Forums are useless, i’ve never got a reply in shorter than a few weeks of waiting, and even then they’ve never solved my issues.

Pretty useless when you’be got to meet deadlines.

Thanks for this!

#39 Chad on 05.23.08 at 6:42 am

You can always do it as a 1 liner…

string userId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();

#40 Tim Cross on 06.04.08 at 8:30 pm

Thank you so much, and to Scott for the VB version. And thanks to Google for finding this solution so quickly :)

#41 Ddon on 06.26.08 at 7:23 am

I am getting this error
MembershipUser user = Membership.GetUser((sender as CreateUserWizard).UserName);
string UserID = user.ProviderUserKey.ToString();
Response.Write(UserID);

Object reference not set to an instance of an object.

Any Idar Please Help..

#42 alesin on 07.28.08 at 4:25 pm

For Ddon.

Maybe:

Membership.GetUser() is definitely null in your case. Meaning that the user
has not actually been logged in

#43 muadib on 08.01.08 at 11:24 pm

Thanks!

#44 daniel on 09.01.08 at 3:58 pm

Membership.GetUser() gets the currently logged in user. If you are trying to GetUser() during log in it will always be null.

You have to do GetUser() AFTER the user is logged in, which means AFTER the page lifecycle of logging in.

I have run into this same problem. What I am doing now is using GetUser(UserName) which doesn’t depend on the user being authenticated.

#45 Brian on 09.12.08 at 11:02 am

I am trying to write to a dataset and I am having trouble with the first parameter which is looking for a system.guid.

1) I attempted to retrieve the logged in users id, but it gives this error: Can’t convert from object to system.guid. (see code at bottom)

2)I also tried making it a string and it gives this error: cannot convert from string to system.guid.

3)on yet another attempt, I replaced object id = User.ProviderUserKey; with System.Guid id = User.ProviderUserKey;

and got this error: Cannot implicitly convert type ‘object’ to ‘System.Guid’. An explicit conversion exists (are you missing a cast?)

what am I doing wrong?

protected void Button1_Click(object sender, EventArgs e)
{
MembershipUser User = Membership.GetUser();
object id = User.ProviderUserKey;//this seems to get the logged in user as an object, but what do I do with it?

string pn = PartNumber.Text;
int q = Int32.Parse(Quantity.Text);
DateTime dd = DDate.SelectedDate;

QuoteDataTableAdapters.Quote_DataTableAdapter da = new GNP_Machining.QuoteDataTableAdapters.Quote_DataTableAdapter();

da.QuoteDataInsert(id, pn, q, dd, Material.Text, SpecialInstructions.Text, null, DateTime.Now, null, DateTime.Now);

#46 kulermaster on 10.03.08 at 11:42 am

Actually this was there all the time. However i admire that you are the one who dug out this quick tip for us. Thanks for that.

#47 Jason on 10.05.08 at 8:24 pm

Perfect! Exactly what I was looking for, I knew there had to be an easy way to get the UserID

#48 Pete Hurst on 10.06.08 at 12:14 pm

It should be pointed out that Membership.GetUser() actually performs a full SELECT query to get the user record from the database.

I had an app grind to a halt because I was using GetUser every time I wanted the user’s ID. For various reasons this was happening thousands of times in a single page request. Thousands of “SELECT FROM aspnet_Users”!

So, if you’re using this function, do it once and save the result.

I’m looking for a way of performing this without having to use Membership.GetUser(). Surely the ID must be held somewhere prior to this call? Do I really have to request a database record, just to find the ID of whoever is logged in?

/serializer

#49 joe on 11.05.08 at 4:41 pm

MembershipUser currentLoggedInUser = Membership.GetUser();
Guid g = new Guid(currentLoggedInUser.ProviderUserKey.ToString());

#50 Jeremy Lake on 12.14.08 at 11:44 am

“I had an app grind to a halt because I was using GetUser every time I wanted the user’s ID” – Peter Hurst

The GetUser() method has been over-loaded so you can pass in a username, email or a userid (provider key/GUID/uniqueidentifier)

I don’t know about asp.net v1.x but in asp.net v2+ it fires stored procedures to get the data and if you look in one of those sprocs, e.g. aspnet_Membership_GetUserByUserId
it specifically says select top 1. This should be pretty quick with all those indexes even though it is a union query, one row is returned.

a couple things that come to mind after reading through some of the posts – that many of you are probably already aware of – are:

1: (try to) never call a database for data that you already have retrieved unless you suspect it has changed.

2: Never ever do that lazy-ass-developer SQL call in any kind of loop, e.g. if you have to do any kind of looping over a collection of users/companies/orders then even just selecting the whole table into a Hashtable and iterating over that will be many times faster, i.e. one sql call not hundreds (watch out server memory)

3: if you use code like “MembershipUser user = Membership.GetUser((sender as CreateUserWizard).UserName);” in any kind of production then your gonna need a try catch block because you can never guarantee that UserName is not null before the GetUser call, (unless it is in some ‘onSuccess’ routine)

once you have the user logged in: FormsAuthentication.SetAuthCookie(theUserName, true); and have one of the ‘Identity.Name’ derivatives working then put your reusables either in a viewstate or in a session state. these are ever .NET developers best friends.

Probably there are better ways but you need to do null checks because and empty string and null are NOT the same thing.

string userName = User.Identity.Name;
if (!String.IsNullOrEmpty(userName))
{
MembershipUser mu = Membership.GetUser(userName);
if (mu != null)
{
Session["MyUserID"] = mu.ProviderUserKey.ToString();
//ViewState["MyUserID"] = mu.ProviderUserKey.ToString();
}
}

if (!String.IsNullOrEmpty(userName))
{
/* and then back somewhere near Page_Load with postback checks */
if (Session["MyUserID"] != null)
{
string myUserID = Session["MyUserID"].ToString();
//MembershipUser mu = Membership.GetUser(myUserID); //This also works i.e. Get By UserID

}
}

It is still beyond me why Microsoft didn’t put an integer identity columns on each of the asp.net tables

#51 Kjella on 04.21.09 at 9:47 pm

Thanks alot, until now I have retrieved it from the user table, but why not use the inbuild methods :)

#52 Marin on 05.29.09 at 2:24 pm

I found it.
Just want to share it with you if somebody needs it:
First have to convert the string to Guid and the to call the method:

Guid UserID = new Guid(“57b0c146-9b75-433b-a6ac-30b598bdbbef”);
Label1.Text= Membership.GetUser(UserID).UserName.ToString();

Good luck

#53 Ian on 12.07.09 at 5:17 am

Thanks heaps!
Fantastic and easy (just the way I like it).

I have to agree with Lulu (Comment 38), ASP.NET forums were less than helpful.
You saved my bacon!
Cheers,

#54 Jimmy Sigenstrøm on 04.20.10 at 4:17 pm

Super nice post.!

And you better believe that this post helps ;o)

#55 phil on 12.03.10 at 11:53 pm

Yep, a real time saver and simple too.

Thanks

#56 G on 05.09.11 at 3:48 am

Beautiful! Posted so long ago and still helped me with ASP.NET 4.0 in MVC3. Thank you!

#57 Sami on 06.15.11 at 9:14 pm

I Love you

Leave a Comment