如何检查用户是否在 Action 中获得授权 [英] How to check if user is authorized inside Action
问题描述
通常我使用 [Authorize]
保护我的操作,但这次我需要检查用户是否在操作中获得授权.
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
}
我相信我正在使用表单身份验证"
I believe I am using 'Forms Authentication'
这个问题有点类似于 this 但给出的答案似乎都不起作用.
This question is kind of similar to this but none of the answers given seemed to work.
我已经做了更多的挖掘 - 似乎如果我在具有 [Authorize]
的 Action 上设置断点,User.Identity 已设置,但在没有它的 Actions 上,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")) { ... }
User
实例是 Controller
类的公共属性,因此您始终可以从您编写的控制器访问它.如果没有用户登录,您应该为 User
设置一个 GenericPrincipal
,为 User.Identity
设置一个 GenericIdentity
,所以不用担心检查空值.
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.
这篇关于如何检查用户是否在 Action 中获得授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!