问题
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