如何有效地测试action是否用属性(AuthorizeAttribute)修饰?
我正在使用 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;
}
}
}
这有点像稍微错误的标题“
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地使用filterContext.ActionDescriptor.GetCustomAttributes
You can simply use filterContext.ActionDescriptor.GetCustomAttributes
var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), false);
http://msdn.microsoft.com/en-us/library/system.web.mvc.actiondescriptor.isdefine%28v=vs.98%29.aspx
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