An awesome routing engine for ASP.NET MVC 3 and 4
Fooaction would be reached using either
~/foo/FirstUglyValueor
~/foo/SecondUglyValueand this behavior can't be changed:
public enum MyEnum { FirstUglyValue, SecondUglyValue } public class MyController : Controller { public ActionResult Foo(MyEnum bar) { return Content("Baz!"); } }
public static void RegisterRoutes(RouteCollection routes) { // ... routes.MapRoute("MyUglyRoute", "{action}/{bar}", new { controller = "MyController", }); // ... }
EnumUrlattribute the fields you wish to map, along with the URL segment itself.
EnumUrlattribute:
public enum MyEnum { [EnumUrl("first")] FirstUglyValue, [EnumUrl("second")] SecondUglyValue } public class MyController : Controller { [Route.Action("~/foo")] public ActionResult Foo([Route.Param] MyEnum bar) { return Content("Baz!"); } }
~/foo/firstor
~/foo/second, possibly with a much higher SEO ranking.
EnumUrlMapperRegistrywhich allows to easily define application-wide mappers for your enumerations, by way of implementations of the
IEnumUrlMapperinterface. The usage is very simple, as the
IEnumUrlMapperinterface has just two methods:
MapFieldNameToUrl()and
MapUrlToFieldName(), which do exactly what their names suggest. Furthermore, SEO Extensions comes with a useful
IEnumUrlMapperimplementation named
DictionaryEnumUrlMapperthat allows bidirectional links between URLs and field names (something you may wish most of the times).
MyEnumhas been defined in assembly you can't modify to add the
EnumUrlattributes, the next example shows how you would obtain the same results while adding an enum mapper to the
EnumUrlMapperRegistryand leaving the action as it was:
public class MyController : Controller { [Route.Action("~/foo")] public ActionResult Foo([Route.Param] MyEnum bar) { return Content("Baz!"); } }
public static void RegisterRoutes(RouteCollection routes) { // ... var coolMapper = new DictionaryEnumUrlMapper<MyEnum>(); coolMapper.Map(MyEnum.FirstUglyValue, "first") coolMapper.Map(MyEnum.SecondUglyValue, "second") EnumUrlMapperRegistry.Register(typeof(MyEnum), coolMapper); // ... }