I am using the MVC4 framework and in a lot of instances throughout the code I want to get the current user ID.
I understand to do this I can use:
[InitializeSimpleMembership]
public ActionResult SaveTask(FormCollection form)
{
var userID = WebSecurity.CurrentUserID;
}
This works Correctly but I find myself having to put the [InitializeSimpleMembership]
on every ActionResult
. Ideally I would like a static function which I can call:
var userID = Utilities.CurrentUserID;
which is in a class called Utilities:
public static Int32 CurrentUserID{
get
{
return WebSecurity.CurrentUserID;
}
}
Note I know this will fail as WebSecurity
will need the InitializeSimpleMembership Attribute
but but I want to show by example what I want to achieve. Is this possible?
You can add the [InitializeSimpleMembership]
to the top of your controller instead of for each action and can use WebSecurity.GetUserId(User.Identity.Name)
Or you can use
var userId = Membership.GetUser(User.Identity.Name).ProviderUserKey;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.