如何有效地测试动作是否用属性(AuthorizeAttribute)装饰? [英] How to efficiently test if action is decorated with an attribute (AuthorizeAttribute)?
问题描述
我正在使用MVC,并且遇到一种情况,在我的 OnActionExecuting()
中,我需要确定要执行的Action方法是否装饰有属性,即 AuthorizeAttribute
.我不是在问授权是否成功/失败,而是在问方法是否需要授权.
I'm using MVC and have a situation where in my OnActionExecuting()
I need to determine if the Action method that is about to execute is decorated with an attribute, the AuthorizeAttribute
in particular. I'm not asking if authorization succeeded/failed, instead I'm asking does the method require authorization.
对于非mvc的人 filterContext.ActionDescriptor.ActionName
是我正在寻找的方法名称.但是,它不是当前正在执行的方法.相反,这是一种将很快执行的方法.
For non-mvc people filterContext.ActionDescriptor.ActionName
is the method name I'm looking for. It is not, however, the currently executing method; rather, it is a method that will be executed shortly.
目前,我有一个类似下面的代码块,但是我对每次操作之前的循环都不满意.有更好的方法吗?
Currently I have a code block like below, but I'm not terribly pleased with the looping prior to every action. Is there a better way to do this?
System.Reflection.MethodInfo[] actionMethodInfo = this.GetType().GetMethods();
foreach(System.Reflection.MethodInfo mInfo in actionMethodInfo) {
if (mInfo.Name == filterContext.ActionDescriptor.ActionName) {
object[] authAttributes = mInfo.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), false);
if (authAttributes.Length > 0) {
<LOGIC WHEN THE METHOD REQUIRES AUTHORIZAITON>
break;
}
}
}
This is a little like the slightly mistitled "How to determine if a class is decorated with a specific attribute" but not quite.
推荐答案
您可以简单地使用filterContext.ActionDescriptor.GetCustomAttributes
You can simply use filterContext.ActionDescriptor.GetCustomAttributes
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool hasAuthorizeAttribute = filterContext.ActionDescriptor
.GetCustomAttributes(typeof(AuthorizeAttribute), false)
.Any();
if (hasAuthorizeAttribute)
{
// do stuff
}
base.OnActionExecuting(filterContext);
}
这篇关于如何有效地测试动作是否用属性(AuthorizeAttribute)装饰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!