2016-07-20 40 views
0

我有這樣爲什麼不捕獲[HttpGet]和[HttpPost]屬性?

foreach(var controller in controllers) 
{ 
    // ... 
    var actions = controller.GetMethods() 
          .Where(method => method.ReturnType == typeof(IHttpActionResult)); 
    foreach(var action in actions) 
    { 
     // ... 
     var httpMethodAttribute = action.GetCustomAttributes(typeof(System.Web.Mvc.ActionMethodSelectorAttribute), true).FirstOrDefault() as System.Web.Mvc.ActionMethodSelectorAttribute; 
     // ... 
    } 
} 

一段代碼,但由於某種原因httpMethodAttribute總是null即使我可以證實,actionCustomAttributeis一個System.Web.Mvc.ActionMethodSelectorAttribute。任何想法我做錯了什麼?

+0

如果我的回答很滿意,你會介意接受它?如果沒有,讓我知道,我會擴大它。 – Amy

回答

2

GetCustomAttributes(..., true)只獲取您指定的確切類型的屬性,搜索您要調用的成員的繼承層次結構GetCustomAttributes。它不會獲得從您正在搜索的屬性類型繼承的屬性。要獲得HttpGetAttribute,您需要致電GetCustomAttributes(typeof(HttpGetAttribute), true)。與HttpPostAttribute一樣的東西。

例如,如果你有一個動作方法Foo從父控制器覆蓋的方法,以及家長的Foo有一個屬性,第二個參數會告訴GetCustomAttributes是否返回父母自定義屬性。

0

一年爲時已晚,但如果你希望得到的HttpMethodAttribute:

var httpMethodAttr = (HttpMethodAttribute)action.GetCustomAttributes() 
         .SingleOrDefault(a => typeof(HttpMethodAttribute).IsAssignableFrom(a.GetType()); 

,或者類型是你所追求的

var httpMethodType = (from a in action.GetCustomAttributes() 
         let t = a.GetType() 
         where typeof(HttpMethodAttribute).IsAssignableFrom(t) 
         select t).SingleOrDefault(); 
if (httpMethodType = null || httpMethodType == typeof(HttpGetAttribute)) 
相關問題