如何在两个控制器操作之间避免AmbiguousMatchException?

我有两个具有相同名称但具有不同方法签名的控制器操作。 它们看起来像这样:

// // GET: /Stationery/5?asHtml=true [AcceptVerbs(HttpVerbs.Get)] public ContentResult Show(int id, bool asHtml) { if (!asHtml) RedirectToAction("Show", id); var result = Stationery.Load(id); return Content(result.GetHtml()); } // // GET: /Stationery/5 [AcceptVerbs(HttpVerbs.Get)] public XmlResult Show(int id) { var result = Stationery.Load(id); return new XmlResult(result); } 

我的unit testing没有调用一个或另一个控制器动作的问题,但我的测试html页面抛出System.Reflection.AmbiguousMatchException。

 Show the stationery Html Show the stationery 

需要改变什么来使这项工作?

只需要一个像这样的方法。

 [AcceptVerbs(HttpVerbs.Get)] public ActionResult Show(int id, bool? asHtml) { var result = Stationery.Load(id); if (asHtml.HasValue && asHtml.Value) return Content(result.GetHtml()); else return new XmlResult(result); } 

这是一个你可能会发现有用的链接。 它谈到了重载MVC控制器。

有两种方法可以解决这个问题:

1>更改方法名称。 2>为这两种方法提供不同的ActionName属性。 您可以定义自己的属性。

ActionName属性。 看一看。

要解决此问题,您可以编写一个ActionMethodSelectorAttribute来检查每个操作的MethodInfo ,并将其与发布的Form值进行比较,然后拒绝任何表单值不匹配的方法(当然不包括按钮名称)。

这是一个例子: – http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/

您还可以创建一个更简单的ActionMethodSelectorAttribute ,它只查看提交按钮名称,但会更紧密地绑定您的控制器和视图。