如何解决如何有效地测试动作是否用属性AuthorizeAttribute装饰?
| 我正在使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。