Get UserId (int) in new MVC4 application

白昼怎懂夜的黑 提交于 2019-11-29 04:39:00

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;

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.

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.

You can get UserId

if (Request.IsAuthenticated)
 {
  var membership = (SimpleMembershipProvider)Membership.Provider; 
  int idUser = membership.GetUserId(User.Identity.Name);
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!