Get UserId (int) in new MVC4 application
Asked Answered
W

4

6

New MVC4 application created UserProfile table :

UserId(int) | UserName(nvarchar)

In controller :

  string currentUser = User.Identity.Name;  // returns UserName

  var mu1 = Membership.GetUser(); // returns null

  var mu2 = Membership.GetUser(currentUser); // returns null as well

I read a lot of threads and they all talk about getting Guid, which I don't even have in user and membership tables.

Is there a way to get the UserId (int) of currently logged in User ?

Wholewheat answered 2/3, 2013 at 22:59 Comment(4)
Why do you need the id?Tobietobin
@andri, to store ad FK in another table.Wholewheat
Why not use the username as FK? The username is unique, isn't it?Tobietobin
@Tobietobin you should be careful when using a user name in this manner because you may have the situation where a user deletes or changes their name, then another user registers with the same username... there could be trouble!Nubble
N
12

Make sure you add [InitializeSimpleMembership] to the top of your controller so that it initializes the simple membership via the file InitializeSimpleMembershipAttribute.cs in the Filters directory.

Then you can access the user id in several different ways:

int mu1 = (int)WebSecurity.CurrentUserId;
int mu2 = (int)Membership.GetUser().ProviderUserKey;
Nubble answered 13/3, 2013 at 10:28 Comment(1)
My InitializeSimpleMembershipAttribute is located in Filters\InitializeSimpleMembershipAttribute so I added using RecreationalServicesTicketingSystem.Filters; on the top of my controller but my int mu1 = (int)WebSecurity.CurrentUserId; gives me The name 'Websecurity' does not exist in the current context. So I used using WebMatrix.WebData;` will this still work?Haiku
G
3

You can get UserId as int with

WebSecurity.GetUserId(User.Identity.Name);

Additional Information: You should add [InitializeSimpleMembership] on top of controller class if you use another controller than AccountController.

Georgiannageorgianne answered 2/3, 2013 at 23:10 Comment(0)
T
0

mu1 and mu2 will contain an instance of MembershipUser if the user has successfully authenticated. MembershipUser has a ProviderUserKey property of type object that will contain the identifier for a user.

Membership.GetUser() requires a MembershipProvider to be hooked up for the application and for the user to be authenticated; since you are seeing null returned, this would suggest that one of the aforementioned conditions is not met.

Tieshatieup answered 2/3, 2013 at 23:7 Comment(0)
D
0

You can get UserId

if (Request.IsAuthenticated)
 {
  var membership = (SimpleMembershipProvider)Membership.Provider; 
  int idUser = membership.GetUserId(User.Identity.Name);
 }
Deoxyribose answered 2/11, 2014 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.