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= "" }
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With