How do I get http verb attribute of an action using refection - ASP.NET Web API

こ雲淡風輕ζ 提交于 2019-12-03 13:53:42
var methodInfo = MethodBase.GetCurrentMethod();
var attribute = methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().FirstOrDefault();

You were very close...

The difference is that all 'verb' attributes inherit from 'ActionMethodSelectorAttribute' including the 'AcceptVerbsAttribute' attribute.

I just needed this and since there has been no answer addressing the actual requirement for Web Api attributes, I've posted my answer.

Web Api attributes are the following:

  • System.Web.Http.HttpGetAttribute
  • System.Web.Http.HttpPutAttribute
  • System.Web.Http.HttpPostAttribute
  • System.Web.Http.HttpDeleteAttribute

Unlike their Mvc counterparts, they do not inherit from a base attribute type, but inherit directly from System.Attribute. Therefore you need to manually check for each specific type individually.

I've made a small extension method that extends the MethodInfo class like so:

    public static IEnumerable<Attribute> GetWebApiMethodAttributes(this MethodInfo methodInfo)
    {
        return methodInfo.GetCustomAttributes().Where(attr =>
            attr.GetType() == typeof(HttpGetAttribute)
            || attr.GetType() == typeof(HttpPutAttribute)
            || attr.GetType() == typeof(HttpPostAttribute)
            || attr.GetType() == typeof(HttpDeleteAttribute)
            ).AsEnumerable();
    }

Once you have got the MethodInfo object for your controller action method by reflection, calling the above extension method will get you all of the action method attributes currently on that method:

    var webApiMethodAttributes = methodInfo.GetWebApiMethodAttributes();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!