c# - 如何获取 Controller 的 POST 操作方法?

标签 c# .net asp.net-mvc unit-testing reflection

我需要对我的 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

最佳答案

更改以下内容:

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

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

这应该有效。

关于c# - 如何获取 Controller 的 POST 操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14343850/

相关文章:

javascript - window.location.href 和 top.location.href 的区别

asp.net-mvc - ASP.Net MVC - 使用外部 URL 进行表单例份验证

c# - 是否可以将推送通知从 ASP.NET MVC4 表单发送到 Windows Azure 移动服务

c# - JavaScriptSerializer 反序列化为嵌套对象

c# - Gridview 分页 ASP.NET 在 Gridview 之外使用寻呼机面板

c# - 处理控件自动相互更新的最佳方法?

c# - 在重写的 void 中运行异步方法

c# - 如何单元测试使用中断对话框取消返回到 MainDialog 的对话框

c# - JIT 编译器如何处理值类型?

c# - 什么可能导致 System.Windows.Forms.InputLanguage.CreateInputLanguageChangingEventArgs 中的溢出异常