找到多个控制器类型匹配请求 URL

Multiple controller types were found that match the Requested URL

我在路由配置文件中启用了属性路由并且我已经将属性路由声明为

[RoutePrefix("receive-offer")]
public class ReceiveOfferController : Controller
{
    // GET: ReceiveOffer
    [Route("{destination}-{destinationId}")]
    public ActionResult Index(int destinationId)
    {
        return View();
    }
}


public class DestinationController : Controller
{
    [Route("{country}/{product}-{productId}")]
    public ActionResult Destination(string country, string product, int productId)
    {
        return View();
    }

}

以上两个控制器,一个是静态前缀,一个是变量前缀 但我发现 Multiple controller types were found that match the URL error from these two controller.

这个路由模式有什么问题。

当属性路由匹配多个路由时会出现这种情况你可以看看这个Multiple controller types were found that match the URL。所以当你输入 domain/receive-offer/new york-1 时,它匹配第一条路线和第二条路线 URL 因为它会将 receive-offer 视为一个国家所以要解决这个问题我们可以使用 路线约束 指定路线的值,这样您的路线将是

 [RoutePrefix("receive-offer")]
    public class ReceiveOfferController : Controller
    {
        // GET: ReceiveOffer
        [Route("{destination}-{destinationId:int}")]
        public ActionResult Index(int destinationId)
        {
            return View();
        }
    }


    public class DestinationController : Controller
    {
        [Route("{country:alpha}/{product}-{productId:int}")]
        public ActionResult Destination(string country, string product, int productId)
        {
            return View();
        }
     }

因为 destinationIdproductId 将是 int 类型,而 country 将是 alphabet 但请记住,如果您在国家/地区中添加空格命名该路线将不起作用,因此您必须申请 regax 或者您可以删除国家名称之间的空格,例如 HongKong