【问题标题】:Multiple controller types were found that match the Requested URL找到多个与请求的 URL 匹配的控制器类型
【发布时间】:2017-09-20 14:18:39
【问题描述】:

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

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

}

在上述两个控制器中,一个具有静态前缀,另一个具有可变前缀 但我发现多个控制器类型与这两个控制器的 URL 错误匹配。

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

【问题讨论】:

  • 可以显示网址吗?
  • url 将类似于 (domain/receive-offer/new york-1)////////// (domain/usa/new york-1) 在上述两个 url usa可以替换为接收报价为静态的任何其他国家/地区。

标签: asp.net-mvc asp.net-mvc-4 routing asp.net-mvc-routing


【解决方案1】:

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

 [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 的类型为intcountry 的类型为alphabet,但请记住,如果您在国家/地区名称中添加空格,则该路线将不起作用,因此您必须申请regax 或者您可以删除国家名称之间的空格,例如 HongKong

【讨论】:

  • 您能否证明在 DestinationController 路由中国家后使用 :alpha 的目的。或任何我可以寻找的参考
  • @Bhuban 其所谓的路由约束意味着指定路由中值的类型,这里的 alpha 表示字母字符(a-z,A-Z)。您可以阅读attribute-routing 部分路线约束
  • 我用它来使路由有点独特的原因是因为receive-offer 是一个字符串并且匹配路由{country} 所以通过添加alpha {country:alpha} 意味着它不会包含任何特殊字符,如@ 987654337@
  • 谢谢@Usman,我的上述要求已经满足,但现在我遇到了另一个问题。在我不想要属性路由并且只想通过域/控制器执行索引操作的控制器中,它正在执行 DestinationController 索引操作,因为域/{country} 与域/{controller} 匹配我应该如何处理这个。跨度>
  • @Bhuban 你可以命名索引[Route("Destination")]
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多