Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UserId (int) in new MVC4 application

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 ?

like image 432
mishap Avatar asked Mar 02 '13 22:03

mishap


2 Answers

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.

like image 31
Mahmut Ali ÖZKURAN Avatar answered Oct 04 '22 11:10

Mahmut Ali ÖZKURAN


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;
like image 63
Garrett Fogerlie Avatar answered Oct 04 '22 12:10

Garrett Fogerlie