2011-04-02 119 views
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... 
    } 
} 

無論如何,我問了一個稍微不同的問題,所以仍然會給出答案要點;)

回答

0

相信該項目執行上的每個方法調用過,但你可以爲實例引用:

 
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%確定在這個上面,但是應該測試上面的代碼,回答你的問題)

希望它可以幫助:)

+0

Thnaks亞當,但ActionName屬性存在位指示級別的屬性了。 – 2011-04-06 21:27:40

相關問題