Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 952
cda01 Avatar asked May 24 '12 01:05

cda01


People also ask

What are the possible HTTP request verbs in Web API?

The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively.

What is the default HTTP verb in Web API?

Default is [HTTPPost] if the method name doesn't match any HTTPVerb.

How do you call an action method in Web API?

Default Action Methods In Web API, Get, Post, Put, and Delete verbs are used as corresponding action methods- Get(), Post ([FromBody]string value), Put (int id, [FromBody]string value), Delete (int id) for manipulating data like get, insert, update and delete.


1 Answers

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.

like image 166
Elie Avatar answered Nov 01 '22 07:11

Elie