Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc routing without a controller or action name

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

For example, the url mywebsite.com/newyork should be processed as 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:

        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= "" }
        );
like image 271
yqit Avatar asked Sep 24 '14 05:09

yqit


1 Answers

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.

like image 73
Carl Avatar answered Nov 07 '22 12:11

Carl