1
當屬性觸發時,我可以測試是否在控制器或操作上設置了屬性?測試屬性是否在控制器或操作上
我想要的行爲是:使用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...
}
}
無論如何,我問了一個稍微不同的問題,所以仍然會給出答案要點;)
Thnaks亞當,但ActionName屬性存在位指示級別的屬性了。 – 2011-04-06 21:27:40