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 ↓
Oh yea, thanks. Google is your friend
I asked on asp.net for those few lines but didn’t get an answer, until now, thanks!
If I have this code inside a class, should I use a httpcontext ?
I am not sure when I have to use HttpContext.Current
In this case you don’t have to use HttpContext, Membership is globally available.
Thank u ,Very much !
Spent a long time looking for this else where. Your a star!
thanks it very usfull could you please give some code sample i tried to get the userid i could not
many thanks
Man that saved a headache! Thank you!!!
Thank you guy!!
As simple as that. Thank you so much.
When I try to use this I get:
Membership does not contain a definition for GetUser(). Am I missing something?
Thanks.
Cheers mate! After 2 hours of google, finally a straight forward answer!
Nice one! Many thanks~
Translation to VB.NET
Dim UserID As String
Dim MemUser As MembershipUser
MemUser = Membership.GetUser()
UserID = MemUser.ProviderUserKey.ToString()
Helpful tip out there
But how to get the userid when creating a user using createuserwizard of asp.net 2.0
Hi shazi, you can use this here:
29 MembershipUser user = Membership.GetUser((sender as CreateUserWizard).UserName);
30 string UserID = user.ProviderUserKey.ToString();
hth,
Andreas
I love you – thanks.
I am definately bookmarking your blog.
Yesssssss.. I was always think there is some way microsoft developers implemented to get user GUID.. Thanx alot
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!
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.
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
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
trialblazer,
you’d have to use something like:
MembershipUser myuser = Membership.GetUser(UserName)
hth,
Andreas
Thanks, that’s what I have been looking for.
Simple! Thanks a ton!
I’ve been looking for this for a while now – thanks!
Thanks a lot
Thanks a lot,
This is very helpfull for me,
May Allah success you….
Thank you this helps.
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=”" />
Thx for this hint
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!
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.
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”);
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?
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!
You can always do it as a 1 liner…
string userId = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
Thank you so much, and to Scott for the VB version. And thanks to Google for finding this solution so quickly
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..
For Ddon.
Maybe:
Membership.GetUser() is definitely null in your case. Meaning that the user
has not actually been logged in
Thanks!
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.
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);
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.
Perfect! Exactly what I was looking for, I knew there had to be an easy way to get the UserID
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
MembershipUser currentLoggedInUser = Membership.GetUser();
Guid g = new Guid(currentLoggedInUser.ProviderUserKey.ToString());
“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
Thanks alot, until now I have retrieved it from the user table, but why not use the inbuild methods
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
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,
Super nice post.!
And you better believe that this post helps ;o)
Yep, a real time saver and simple too.
Thanks
Beautiful! Posted so long ago and still helped me with ASP.NET 4.0 in MVC3. Thank you!
I Love you
Leave a Comment