【发布时间】:2011-07-28 03:03:11
【问题描述】:
当一个 Attribute 触发时,我可以测试是在 Controller 还是 Action 上设置的吗?
我想要的行为是:如果存在则使用 Action 属性,否则使用 Controller 属性。像这样的:
public class TestAttribute : FilterAttribute, IAuthorizationFilter
{
public TestAttribute(string optionalParam = "") { /*...*/ }
public void OnAuthorization(AuthorizationContext filterContext)
{
bool isClassAttribute; // = ????
bool hasActionAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(TestAttribute ), false).Length > 0;
if (isClassAttribute && hasActionAttribute)
return; // handle in Action attribute
else
; // do stuff with optionalParam...
}
}
[TestAttribute]
public class TestClass
{
[TestAttribute(optionalParam:"foo"]
public ActionResult TestMethod() { return null; }
}
我可以使用 Order 属性执行此操作,但不想每次都设置它(或 get funky)。
编辑/解决方案
好的,找到了我的问题的解决方案(但不是问题) - 设置属性基本参数 AllowMultiple=false 意味着 last instance of the same filter type is allowed, and all others are discarded (并且控制器属性首先运行(?)所以应该很好去......)。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class TestAttribute : FilterAttribute, IAuthorizationFilter
{
public TestAttribute(string optionalParam = "") { /*...*/ }
public void OnAuthorization(AuthorizationContext filterContext)
{
// this should be the Action attribute (if exists), else the Controller attribute...
}
}
无论如何我问了一个稍微不同的问题,所以仍然会给出答案;)
【问题讨论】:
标签: asp.net-mvc custom-attributes