【发布时间】:2017-10-12 15:30:59
【问题描述】:
我正在尝试从 API 控制器获取属性标记,以便我可以查看它在运行时允许的 HTTP 动词。从下面的示例代码中,我希望能够获得[HttpGet] 标签。
[HttpGet]
public void MyResource()
{
// Controller logic
}
我目前正在使用System.Reflection 在它运行时收集有关我的 API 的其他信息,但到目前为止我无法检索到 [HttpGet 标记和其他 Http 动词标记。我已经尝试了以下每个解决方案,但都没有成功:
public void GetControllerMethodHttpAttribute()
{
MethodInfo controllerMethod = typeof(TestController).GetMethods().First();
// Solution 1
var attrs = controllerMethod.Attributes;
// Solution 2
var httpAttr = Attribute.GetCustomAttributes(typeof(HttpGetAttribute));
// Solution 3
var httpAttr2 = Attribute.GetCustomAttribute(controllerMethod, typeof(HttpGetAttribute));
// Solution 4
var httpAttr3 = Attribute.IsDefined(controllerMethod, typeof(HttpGetAttribute));
}
我之前研究过的关于这个主题的所有问题都只与Custom Attribute tags 相关并从中提取值,但我找不到任何有关获取包含框架的Attribute tags 的信息。
有人知道我如何获得[HttpGet] 属性标签吗?
谢谢!
【问题讨论】:
-
你需要“这个动作支持get/post/etc”,还是属性里面的完整信息(订单、模板等)?
-
你确认
typeof(TestController).GetMethods().First()返回了预期的方法吗? -
@gunr2171 最好提供完整信息,但最重要的是我希望能够说出每种方法支持哪些动词。
-
@thehennyy 该行是对我的应用程序实际操作的简化。我有一段更大的代码,它从给定的控制器类中检索所有方法并遍历每个方法;所以我的实际代码无疑会遇到一个带有
Http标签的方法 -
解决方案 3 适合我。
标签: c# asp.net-mvc reflection