qmsqya
Last Updated: October 11, 2016
·
46.22K
· aviatrix

How to get Current User ID in asp.net MVC 4

After some time i finally figured it out ...

the best way to do so is to use the WebSecurty class
var memberId = WebSecurity.GetUserId(User.Identity.Name);

and don't forget to add
[InitializeSimpleMembership]
on top of your controller :)

7 Responses
Add your response

1262

I think the easiest way is...

var userId = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;

No data attributes needed :)

over 1 year ago ·
2964

The easiest way to get the Current User Id in Asp.Net MVC 4 is

WebSecurity.CurrentUserId

over 1 year ago ·
2965

Or, just to add to my previous comment, you can also use -

WebSecurity.GetUserId(User.Identity.Name)

over 1 year ago ·
5767

Thank you!! this helped me a lot.

over 1 year ago ·
7467

I tried these both code

ViewBag.UserId = WebSecurity.CurrentUserId;

ViewBag.UserId = (int)WebSecurity.CurrentUserId;

but I got same error "You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site."

please help, thx


solve my self :

adding [InitializeSimpleMembership] on the top of controller name, and include Filter using MvcMovie.Filters;

over 1 year ago ·
12360

Include:
using Microsoft.AspNet.Identity;

Then use extension methods:
User.Identity.GetUserId()

over 1 year ago ·
28229

how to implement this code to my controller ?where i should write this code ?

over 1 year ago ·