2016-07-20 79 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)) 
相关问题