How to get http verb attribute for action using refection - ASP.NET Web API

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

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

Suppose I have the above action method in my controller. So far, using reflection, I managed to get the MethodInfo object of the Index action method, which I saved in a variable called methodInfo

I tried to get the http verb using the following, but that didn't work - it returns null:

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

Something I noticed:

My example above is from an ASP.NET Web API project I'm working on.

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

but in normal ASP.NET MVC projects [HttpGet] is System.Web.Mvc.HttpGetAttribute

+6
source share
2 answers
 var methodInfo = MethodBase.GetCurrentMethod(); var attribute = methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().FirstOrDefault(); 

You were very close ...

The difference is that all the 'verb' attributes are inherited from the ' ActionMethodSelectorAttribute ', including the AcceptVerbsAttribute attribute.

+4
source

I just need it, and since there was no answer to the actual requirement of Web Api attributes, I sent my answer.

The attributes of Web Api are as follows:

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

Unlike their Mvc copies, they are not inherited from the base attribute type, but inherited directly from System.Attribute. Therefore, you need to manually check each specific type separately.

I made a small extension method that extends the MethodInfo class as follows:

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

After you have a MethodInfo object for your controller action method by reflection, calling the above extension method will give you all the action method attributes currently used for this method:

  var webApiMethodAttributes = methodInfo.GetWebApiMethodAttributes(); 
+2
source

Source: https://habr.com/ru/post/916511/


All Articles