[英]Global Get Current UserID function
I am using the MVC4 framework and in a lot of instances throughout the code I want to get the current user ID. 我正在使用MVC4框架,并且在整个代码的很多实例中,我都希望获得当前的用户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
. 这可以正常工作,但是我发现自己必须在每个ActionResult
上放置[InitializeSimpleMembership]
。 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. 注意,我知道这将失败,因为WebSecurity
将需要InitializeSimpleMembership Attribute
,但是我想通过示例展示我想要实现的目标。 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)
您可以将[InitializeSimpleMembership]
添加到控制器的顶部,而不是为每个操作添加,并且可以使用WebSecurity.GetUserId(User.Identity.Name)
Or you can use 或者你可以使用
var userId = Membership.GetUser(User.Identity.Name).ProviderUserKey;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.