没有控制器或操作名称的Asp.net mvc路由

15

我想要将所有与现有控制器不匹配的url重定向到特定的控制器。

例如,url mywebsite.com/newyork 应被处理为 mywebsite.com/Cities/Info/newyork

我在我的RegisterRoutes中使用以下代码,但似乎不起作用,因为我得到了404响应:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.MapRoute(
            name: "Cities",
            url: "{cityname}",
            defaults: new { controller = "Cities", action = "Info", cityname= "" }
        );
1个回答

19

你应该将你的城市路线放在第一位,并删除空的默认参数:

    routes.MapRoute(
        name: "Cities",
        url: "{cityname}",
        defaults: new { controller = "Cities", action = "Info" }
    );
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

路由按顺序处理,因此您应该先从最具体的路由开始,再到最不具体的(即默认路由)。

由于您的网站website.com/newyork匹配了默认路由,它没有继续访问您的城市路由。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接