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
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.
Default is [HTTPPost] if the method name doesn't match any HTTPVerb.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With