0

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?

Ms. Corlib
  • 4,993
  • 4
  • 12
  • 19
  • If my answer was satisfactory, would you mind accepting it? If not, let me know and I'll expand on it. –  Jul 29 '16 at 16:53

2 Answers2

3

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.

1

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))
Brent
  • 4,611
  • 4
  • 38
  • 55