qmsqya
Last Updated: October 11, 2016
·
34.91K
· aviatrix
B324968ed50da86db79396915ee5c7d5

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 :)

Say Thanks
Respond

7 Responses
Add your response

1262
B44c977d5c6d7bf0a38bb0170636b31a

I think the easiest way is...

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

No data attributes needed :)

over 1 year ago ·
2964
Default profile 6 normal

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

WebSecurity.CurrentUserId

over 1 year ago ·
2965
Default profile 6 normal

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
Ygx9j6gs normal

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 ?

9 months ago ·