Create a gist now

Instantly share code, notes, and snippets.

Getting nice URLs to work in EPiServer CMS 7 with MVC usually means you have to create an ISegment implementation. This extension method makes it a bit tidier.
using System.Collections.Generic;
using System.Web.Routing;
using EPiServer.Web.Routing;
using EPiServer.Web.Routing.Segments;
namespace Project.Core.Mvc.Routing {
public static class SegmentRouteCollectionExtensions {
public static ContentRoute MapContentRouteWithSegments(this RouteCollection routes, string name, string url, object defaults, params ISegment[] segments) {
return routes.MapContentRouteWithSegments(name, url, defaults, null, segments);
}
public static ContentRoute MapContentRouteWithSegments(this RouteCollection routes, string name, string url, object defaults, MapContentRouteParameters parameters, params ISegment[] segments) {
if (parameters == null)
parameters = new MapContentRouteParameters();
if (parameters.SegmentMappings == null)
parameters.SegmentMappings = new Dictionary<string, ISegment>();
foreach (var segment in segments) {
parameters.SegmentMappings.Add(segment.Name, segment);
}
return routes.MapContentRoute(name, url, defaults, parameters);
}
}
}
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using EPiServer.Framework;
using EPiServer.ServiceLocation;
using EPiServer.Framework.Initialization;
using EPiServer.Web.Routing;
using Project.Core.Mvc.Routing;
namespace Project.Web {
[InitializableModule]
[ModuleDependency(typeof(ServiceContainerInitialization))]
public class RouteConfig : IInitializableModule {
public void RegisterRoutes(RouteCollection routes) {
// example of using the new extension method
routes.MapContentRouteWithSegments(
"ProductPage",
"{language}/{node}/{partial}/{action}/{product}/{page}",
new { controller = "Product", action = "Index", searchTerms = UrlParameter.Optional },
new ProductSegment("product"),
new PageSegment("page")
);
}
public void Initialize(InitializationEngine context) {
RegisterRoutes(RouteTable.Routes);
}
public void Uninitialize(InitializationEngine context) { }
public void Preload(string[] parameters) { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment