如何有效地测试动作是否使用属性(AuthorizeAttribute)进行修饰?

EBa*_*arr 15 c# reflection asp.net-mvc c#-4.0 asp.net-mvc-2

我正在使用MVC,并且OnActionExecuting()我需要确定是否要执行的Action方法是否使用属性进行修饰AuthorizeAttribute,特别是.我不是在问授权是否成功/失败,而是我问这个方法是否需要授权.

对于非mvc人 filterContext.ActionDescriptor.ActionName,我正在寻找的方法名称.但是,它不是当前正在执行的方法; 相反,它是一种即将执行的方法.

目前我有一个像下面这样的代码块,但是我对每个动作之前的循环都不是很满意.有一个更好的方法吗?

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这有点像略有错误的" 如何确定一个类是否用特定属性修饰 "但不完全.

Luk*_*tný 37

您只需使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • ActionDescriptor.IsDefined()也可用于代替ActionDescriptor.GetCustomAttributes().Any()如果​​你想要一个轻微的性能提升. (12认同)

Vla*_*nko 8

var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), false);

http://msdn.microsoft.com/en-us/library/system.web.mvc.actiondescriptor.isdefined%28v=vs.98%29.aspx