问题描述
|
我正在使用MVC,并且遇到一种情况,在我的ѭ0中,我需要确定是否要执行的Action方法是否用属性(尤其是ѭ1)修饰。我不是在问授权是否成功/失败,而是在问方法是否需要授权。
对于非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;
}
}
}
这有点像标题稍有误的“如何确定某个类是否装饰有特定属性”,但不太正确。
解决方法
您可以简单地使用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);
}
,var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute),false);
http://msdn.microsoft.com/zh-cn/library/system.web.mvc.actiondescriptor.isdefined%28v=vs.98%29.aspx