发现多个控制器类型匹配 URL MVC 5.2

Multiple controller types were found that match the URL MVC 5.2

当我点击 url Shop/Checkout

时出现此错误

The request has found the following matching controller types:

  • shopmvc.Controllers.HomeController
  • shopmvc.Controllers.ProductsController

我的HomeController.cs:

[Route("{action=index}")]
public class HomeController : Controller
{
    [Route("Shop/Checkout")]
    public ActionResult Checkout()
    {
    }
}

我的ProductsController.cs:

[RoutePrefix("Shop")]
[Route("{action=index}")]
public class ProductsController : Controller
{
    [HttpGet]
    [Route("{brand}/{category}/{subcategory?}/{page:int?}")]
    public ActionResult Index(string brand, string category, string subcategory, int? page, SortOptions currentSort = SortOptions.SinceDesc)
    {
    }

    [HttpGet]
    [ActionName("Details")]
    [Route("{brand}/{category}/{productid}")]
    public ActionResult Details(int productid)
    {
    }
}

我知道两条路线中都有 Shop,但我不知道如何解决这个问题。这是我共享布局中的剃刀代码:

<a href="@Url.Action("checkout", "Home" )">

问题是 "Checkout" 在您的 ProductController 路由中作为 brand 的参数是有效的。具有属性路由的路由没有内在顺序,因此您必须更加小心以确保只有一条路由可以真正匹配 URL。对于您的情况,您可以简单地执行以下操作:

[Route("{brand:regex((?!Checkout))}/...")]