测试属性是否在控制器或操作上
问题描述:
当属性触发时,我可以测试是否在控制器或操作上设置了属性?测试属性是否在控制器或操作上
我想要的行为是:使用Action属性if exists,否则使用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)设置。
编辑/解决方案
OK,找到了解决我的问题(但不是问题) - 设置属性的基础参数的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...
}
}
无论如何,我问了一个稍微不同的问题,所以仍然会给出答案要点;)
答
相信该项目执行上的每个方法调用过,但你可以为实例引用:
public void OnActionExecuting(ActionExecutingContext filterContext) { } .. .. string controllerName = filterContext.Controller.GetType().Name; //either or: string actionMethodName = filterContext.ActionDescriptor.ActionName; string actionMethodName = filterContext.RouteData.Values["action"].ToString();
如果你的actionMethodName为null,那么它可能来自你的控制器 - 虽然就像我说的,当一个动作方法被调用时它们可能只会被调用(不是100%确定在这个上面,但是应该测试上面的代码,回答你的问题)
希望它可以帮助:)
Thnaks亚当,但ActionName属性存在位指示级别的属性了。 – 2011-04-06 21:27:40