找到了与请求的URL匹配的多种控制器类型

时间:2017-04-24 02:42:21

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

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

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

}

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

此路由模式有什么问题。

1 个答案:

答案 0 :(得分:0)

当属性路由与多个路径匹配时,您可以查看此Multiple controller types were found that match the URL。因此,当您输入domain/receive-offer/new york-1时,它会匹配第一个路由以及第二个网址,因为它会将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

相关问题