如何检查是否用户被授权的内部行动 [英] How to check if user is authorized inside Action
问题描述
通常我保护我的动作与 [授权]
但这次我需要检查,如果一个用户被授权的行动中。
Usually I protect my Actions with [Authorize]
but this time I need to check if a user is authorized inside the action.
例如:
if(userIsAuthorized) {
//do stuff
}
else {
//return to login page
}
<击>我相信罢>我使用窗体身份验证
这个问题是一种类似于<一个href=\"http://stackoverflow.com/questions/1332132/check-if-user-is-logged-in-in-user-control-asp-net-mvc\">this但没有给出的答案似乎工作。
This question is kind of similar to this but none of the answers given seemed to work.
编辑:我已经做了一些更digging-看来,如果我断点,有一个行动 [授权]
中,User.Identity设置,但没有行动它的User.Identity是空的,即使我在我登录
I have done some more digging- it seems if I breakpoint on an Action that has [Authorize]
, the User.Identity is set, but on Actions without it, the User.Identity is empty, even if I am logged in
推荐答案
如果你只是想知道,如果用户登录:
If you just want to know if the user is logged in:
if (User.Identity.IsAuthenticated) { ... }
如果你正在尝试做的任何事情角色特定的:
If you are trying to do anything role-specific:
if (User.IsInRole("Administrators")) { ... }
的用户
的实例会在控制器
类的公共属性,所以你总是有一个从访问它控制器你写。如果没有用户登录,你应该有一个的GenericPrincipal
为用户
和 GenericIdentity
为 User.Identity
,所以不用担心检查空值。
The User
instance is a public property of the Controller
class, so you always have access to it from a Controller you write. If no user is logged in you should have a GenericPrincipal
for the User
and a GenericIdentity
for the User.Identity
, so don't worry about checking for nulls.
这篇关于如何检查是否用户被授权的内部行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!