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

半腔热情 提交于 2019-12-12 07:59:16

问题


I have an ASP.NET Web API project. Using reflection, how can I get the Http verb ([HttpGet] in the example below) attribute which decorates my action methods?

[HttpGet]
public ActionResult Index(int id) { ... }

Assume that I have the above action method in my controller. So far, by using reflection I have been able to get a MethodInfo object of the Index action method which i have stored in a variable called methodInfo

I tried to get the http verb using the following but it did not work - returns null:

var httpVerb = methodInfo.GetCustomAttributes(typeof (AcceptVerbsAttribute), false).Cast<AcceptVerbsAttribute>().SingleOrDefault();

Something I noticed:

My example above is from a ASP.NET Web API project I am working on.

It seems that the [HttpGet] is a System.Web.Http.HttpGetAttribute

but in regular ASP.NET MVC projects the [HttpGet] is a System.Web.Mvc.HttpGetAttribute


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/10730041/how-do-i-get-http-verb-attribute-of-an-action-using-refection-asp-net-web-api

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