You do not need to lose the default route. The key to avoiding your routes getting in the way is to arrange them so that more specific rules precede less specific ones. For example:
// Your specialized route routes.MapRoute( "Page", "Page/{slug}", new { controller = "Page", action = "Index" } ); // Default MVC route (fallback) routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );
Then your PageController will look like this:
using System.Web.Mvc; public class PageController : Controller { public string Index(string slug) {
However, I would strongly advise you to do this:
// Your specialized route routes.MapRoute( "Page", "Page/{id}/{slug}", new { controller = "Page", action = "Index", slug = UrlParameter.Optional } ); // MVC default route (fallback) routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );
And your PageController:
using System.Web.Mvc; public class PageController : Controller { public string Index(int id) {
By including the page id at the beginning of your URL (e.g. StackOverflow) or at the end, you can simply ignore the pool and instead get your pages by id. This will save a ton of headaches if your users change the page name. I survived it, and it is painful; you basically need to record all the names that your pages had in the past, so your visitors / search engines do not get 404 every time the page is renamed.
Hope this helps.
Daniel Liuzzi
source share