如何使用Refection获取动作的HTTP动词属性-ASP.NET Web API [英] How do I get http verb attribute of an action using refection - ASP.NET Web API

查看:71
本文介绍了如何使用Refection获取动作的HTTP动词属性-ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API项目.使用反射,如何获得装饰动作方法的Http动词(在下面的示例中为[HttpGet])属性?

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) { ... }

假设我的控制器中具有上述操作方法.到目前为止,通过反射,我已经能够获取Index动作方法的MethodInfo对象,该对象已存储在名为methodInfo

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

我尝试使用以下命令获取http动词,但该命令不起作用-返回null:

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:

我上面的示例来自我正在研究的ASP.NET Web API项目.

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

[HttpGet]似乎是System.Web.Http.HttpGetAttribute

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

,但是在常规的ASP.NET MVC项目中,[HttpGet]是System.Web.Mvc.HttpGetAttribute

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

推荐答案

var methodInfo = MethodBase.GetCurrentMethod();
var attribute = methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().FirstOrDefault();

你非常亲密...

区别在于,所有动词"属性都继承自" ActionMethodSelectorAttribute ",包括" AcceptVerbsAttribute "属性.

The difference is that all 'verb' attributes inherit from 'ActionMethodSelectorAttribute' including the 'AcceptVerbsAttribute' attribute.

这篇关于如何使用Refection获取动作的HTTP动词属性-ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆