如何获得控制器的POST操作方法?

本文关键字:操作方法 POST 何获得 控制器 | 更新日期: 2023-09-27 17:53:15

我需要对POST操作方法进行单元测试,所以我需要一个它们的列表。我正在使用反射来找到[AcceptVerbs(HttpVerbs.Post)]的这些方法。

// get controller's methods
typeof(FooController).GetMethods()
// get controller's action methods
.Where(q => q.IsPublic && q.IsVirtual && q.ReturnType == typeof(ActionResult))
// get actions decorated with AcceptVerbsAttribute
.Where(q => q.CustomAttributes
  .Any(w => (w.AttributeType == _typeof(AcceptVerbsAttribute)))
  )
// ...everything is ok till here...
// filter for those with the HttpVerbs.Post ctor arg
.Where(q => q.CustomAttributes
  .Any(w => w.ConstructorArguments.Any(e => e.Value.Equals(HttpVerbs.Post))))
;

然而,这给了我一个空列表。问题出在对属性的最后一次检查中。我怎么修理它?

值得注意的是,有两种方法可以将动作的方法声明为POST:像上面那样使用AcceptVerbsAttributeHttpPostAttribute

如何获得控制器的POST操作方法?

修改以下内容:

w => w.ConstructorArguments.Any(e => e.Value.Equals(HttpVerbs.Post))

w => w.ConstructorArguments.Any(e => ((HttpVerbs) e.Value) == HttpVerbs.Post)

应该可以了

你也可以使用[HttpPost]属性代替[AcceptVerbs(HttpVerbs.Post)]来简化你的表达式。

http://msdn.microsoft.com/en-us/library/system.web.mvc.httppostattribute (v = vs.108) . aspx