Asp.net mvc routing without a controller or action name

yqit picture yqit · Sep 24, 2014 · Viewed 7.5k times · Source

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

Answer

Carl picture Carl · Oct 1, 2014

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.