简体   繁体   中英

Why isn't this capturing the [HttpGet] and [HttpPost] attributes?

I have a piece of code like

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;
      // ... 
   }
}

but for some reason httpMethodAttribute is always null even when I can confirm that the action has a CustomAttribute that is a System.Web.Mvc.ActionMethodSelectorAttribute . Any idea what I'm doing wrong?

GetCustomAttributes(..., true) only gets attributes of the exact type you specify, searching up the inheritance hierarchy of the member you're calling GetCustomAttributes on. It doesn't get attributes that inherit from the attribute type you're searching for.

To get a HttpGetAttribute , you'll need to call GetCustomAttributes(typeof(HttpGetAttribute), true) . Same thing with the HttpPostAttribute .

For example, if you have an action method Foo that overrides a method from a parent controller, and the parent's Foo had an attribute, the second parameter would tell GetCustomAttributes whether to return the parents custom attribute.

a year too late, but if you wish to get the HttpMethodAttribute:

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

or if the type is what you are after

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM