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

时间:2022-06-26 17:12:14

I am trying to redirect all urls that don't match an existing controller to a certain controller.

我试图将所有与现有控制器不匹配的URL重定向到某个控制器。

For example, the url mywebsite.com/newyork should be processed as mywebsite.com/Cities/Info/newyork

例如,网址mywebsite.com/newyork应该被处理为mywebsite.com/Cities/Info/newyork

I am using the following code in my RegisterRoutes but it doesn't seem to work as I get a 404 reponse:

我在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 个解决方案

#1


18  

You should put your cities route first and drop the empty default parameter:

您应该首先放置您的城市路线并删除空的默认参数:

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

The routes are processed in order so you should have most specific first to least specific ( your default route).

路线按顺序处理,因此您应该具有最具体的第一个到最不具体的(您的默认路线)。

As your website.com/newyork matched the default route, it wasn't continuing to your city route.

由于您的website.com/newyork与默认路线匹配,因此不会继续您的城市路线。

#1


18  

You should put your cities route first and drop the empty default parameter:

您应该首先放置您的城市路线并删除空的默认参数:

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

The routes are processed in order so you should have most specific first to least specific ( your default route).

路线按顺序处理,因此您应该具有最具体的第一个到最不具体的(您的默认路线)。

As your website.com/newyork matched the default route, it wasn't continuing to your city route.

由于您的website.com/newyork与默认路线匹配,因此不会继续您的城市路线。