c# - 如何避免两个 Controller 操作之间出现 AmbiguousMatchException?

标签 c# .net asp.net-mvc controller

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

    //
    // 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);
    }

我的单元测试调用一个或另一个 Controller 操作没有问题,但我的测试 html 页面抛出 System.Reflection.AmbiguousMatchException。

<a href="/Stationery/1?asHtml=true">Show the stationery Html</a>
<a href="/Stationery/1">Show the stationery</a>

需要更改什么才能使其正常工作?

最佳答案

只有一种这样的方法。

[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);
}

关于c# - 如何避免两个 Controller 操作之间出现 AmbiguousMatchException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/732205/

相关文章:

c# - 将负数转换为无符号类型(ushort、uint 或 ulong)

c# - 无法在 Visual Studio 2012 中调试单元测试项目

.net - MVVM 中的启动逻辑应该放在哪里?

javascript - 使用 javascript 将 [no-cache] 重定向到页面

asp.net-mvc - 在 ASP.NET MVC 中,返回 RedirectToAction 时保留 URL

c# - IsPersistent 在 OWIN Cookie 身份验证中的工作原理

c# - Windows 应用程序在使用后台工作进程时被挂起

c# - 如何通过 New-Variable 将数组变量注入(inject) PowerShell 运行空间

c# - 将字符串拆分为无分隔符的数组

c# - 简单的 C# 数组抛出 OutOfMemory 异常