【问题标题】:How do I get http verb attribute of an action using refection - ASP.NET Web API如何使用反射获取操作的 http 动词属性 - ASP.NET Web API
【发布时间】:2012-05-30 14:20:17
【问题描述】:

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

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

假设我的控制器中有上述操作方法。到目前为止,通过使用反射,我已经能够获得 Index 操作方法的 MethodInfo 对象,我将其存储在一个名为 methodInfo 的变量中

我尝试使用以下方法获取 http 动词,但没有成功 - 返回 null:

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

我注意到的一点:

我上面的示例来自我正在处理的一个 ASP.NET Web API 项目。

看来[HttpGet]是一个System.Web.Http.HttpGetAttribute

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

【问题讨论】:

    标签: asp.net-mvc reflection asp.net-web-api custom-attributes


    【解决方案1】:
    var methodInfo = MethodBase.GetCurrentMethod();
    var attribute = methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().FirstOrDefault();
    

    你们很亲密……

    不同之处在于所有“动词”属性都继承自“ActionMethodSelectorAttribute”,包括“AcceptVerbsAttribute”属性。

    【讨论】:

    • 感谢@Elie,但是,您的解决方案仅适用于 ASP.NET MVC 应用程序,但不适用于 ASP.NET Web API 应用程序。在 WEB API 项目中,http 动词 - HttpGet 与 MVC 项目中的 HttpGet 不同。
    【解决方案2】:

    我只是需要这个,由于没有解决 Web Api 属性的实际要求的答案,我已经发布了我的答案。

    Web Api 属性如下:

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

    与它们的 Mvc 对应物不同,它们不从基本属性类型继承,而是直接从 System.Attribute 继承。因此,您需要单独手动检查每种特定类型。

    我做了一个小扩展方法,像这样扩展 MethodInfo 类:

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

    一旦您通过反射获得了控制器动作方法的 MethodInfo 对象,调用上述扩展方法将获得当前在该方法上的所有动作方法属性:

        var webApiMethodAttributes = methodInfo.GetWebApiMethodAttributes();
    

    【讨论】:

    • 你考虑过:methodInfo.GetCustomAttributes().Where(attr =&gt; attr is IActionHttpMethodProvider)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多