Reputation: 7814
I've set up routing to allow SEO (and human) friendly URLs by allowing a URL in the format ~/{category}/{title}
All of which should route to the content controller which has a method to redirect appropriately. I also want to allow ~/{category}
which takes you to a filtered Index.
All of this works for me using:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Category And Title", // Route name
"{category}/{title}", // URL with parameters
new { controller = "Content", action = "SeoRouting", title = UrlParameter.Optional }, // Parameter defaults
new { category = "People|IT|Personnel|Finance|Procedures|Tools"}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
}
But if the categories change then I'll need to change them in two places. Here in Global.asax and in the enum we have for categories.
In an ideal world I'd like the first route used if the value in the first part of the path matches (case insensitively) the ContentCategory enum and the default route if not.
The categories are going to change really infrequently so this isn't a huge thing but if feels like it should be possible.
Upvotes: 1
Views: 1635
Reputation: 3243
Sorry I am slightly confused as to what the actual question is, but you can get around the "changing code in two places" (sort of) by using the actual enum to generate the regex object:
routes.MapRoute(
"Category And Title", // Route name
"{category}/{title}", // URL with parameters
new { controller = "Content", action = "SeoRouting", title = UrlParameter.Optional }, // Parameter defaults
new { category = getCategories() }
);
private static string getCategories()
{
var categories = Enum.GetNames(typeof(ContentCategory));
return string.Join("|", categories);
}
Upvotes: 12