13

I want to add a user's GUID in with the information I retrieve from a user when they submit a post. How can I get the GUID?

I am using the default authentication system that comes along with an ASP.NET MVC application.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
irl_irl
  • 3,785
  • 9
  • 49
  • 60

4 Answers4

30

If you are using the ASP.NET Membership provider:

MembershipUser user = Membership.GetUser(User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;

or simply:

Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
2

You could simply use the username instead of hitting the database for something like this:

[Authorize]
public ActionResult PostComment()
{
    var username = User.Identity.Name;
    // Here you know the user trying to post a comment
    ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Hmm my plan was to use the GUID as the foreign key. Is it better to use a user's username? – irl_irl Jan 22 '11 at 17:24
  • 1
    I would think that this might be a flaw in the membership library as usernames are something the user chose (thus something they'd want to change) and Guid lookups must be somehow optimized in SQL Server. – James White Mar 02 '12 at 21:42
  • 6
    The username is *not* guaranteed unique or consistent over time. People change their names. Two people employed during different time periods could get the same username; they should *not* end up with a shared history. – brianary Jan 22 '15 at 22:48
1

Hi there is a MVC use of the Membership example, with explanation in this blog. It shows how you can get the membership information of current logged in user.

Anish Nair
  • 43
  • 3
0

This is how to get the user guid from the user name:

Guid userGuid = (Guid)Membership.GetUser(user.Username).ProviderUserKey;
live-love
  • 48,840
  • 22
  • 240
  • 204