简体   繁体   English

为什么不捕获[HttpGet]和[HttpPost]属性?

[英]Why isn't this capturing the [HttpGet] and [HttpPost] attributes?

I have a piece of code like 我有一段代码像

foreach(var controller in controllers)
{
   // ... 
   var actions = controller.GetMethods()
                           .Where(method => method.ReturnType == typeof(IHttpActionResult));
   foreach(var action in actions)
   {
      // ... 
      var httpMethodAttribute = action.GetCustomAttributes(typeof(System.Web.Mvc.ActionMethodSelectorAttribute), true).FirstOrDefault() as System.Web.Mvc.ActionMethodSelectorAttribute;
      // ... 
   }
}

but for some reason httpMethodAttribute is always null even when I can confirm that the action has a CustomAttribute that is a System.Web.Mvc.ActionMethodSelectorAttribute . 但由于某些原因httpMethodAttribute总是null ,即使我可以证实,该actionCustomAttributeis一个System.Web.Mvc.ActionMethodSelectorAttribute Any idea what I'm doing wrong? 知道我在做什么错吗?

GetCustomAttributes(..., true) only gets attributes of the exact type you specify, searching up the inheritance hierarchy of the member you're calling GetCustomAttributes on. GetCustomAttributes(..., true)仅获取与您指定的类型完全相同的属性,并在其上调用GetCustomAttributes的成员的继承层次结构进行搜索。 It doesn't get attributes that inherit from the attribute type you're searching for. 它不会获取从您要搜索的属性类型继承的属性。

To get a HttpGetAttribute , you'll need to call GetCustomAttributes(typeof(HttpGetAttribute), true) . 要获取HttpGetAttribute ,您需要调用GetCustomAttributes(typeof(HttpGetAttribute), true) Same thing with the HttpPostAttribute . HttpPostAttribute相同。

For example, if you have an action method Foo that overrides a method from a parent controller, and the parent's Foo had an attribute, the second parameter would tell GetCustomAttributes whether to return the parents custom attribute. 例如,如果您有一个操作方法Foo覆盖了父控制器的方法,而父方法的Foo具有属性,则第二个参数将告诉GetCustomAttributes是否返回父母自定义属性。

a year too late, but if you wish to get the HttpMethodAttribute: 一年为时已晚,但是如果您希望获取HttpMethodAttribute:

var httpMethodAttr = (HttpMethodAttribute)action.GetCustomAttributes()
                        .SingleOrDefault(a => typeof(HttpMethodAttribute).IsAssignableFrom(a.GetType());

or if the type is what you are after 或者如果类型是您想要的

var httpMethodType = (from a in action.GetCustomAttributes()
                      let t = a.GetType()
                      where typeof(HttpMethodAttribute).IsAssignableFrom(t)
                      select t).SingleOrDefault();
if (httpMethodType = null || httpMethodType == typeof(HttpGetAttribute))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM