Make URLs for EPiServer CMS pages lowercased using a simple initialization module.
By default EPiServer CMS generates URL segments, or routing segments, based on a page’s name. It does this by stripping out special characters and replacing whitespaces with hyphens. It does not however make the URL segments lowercased.
Lars Timenes at Epinova has previously written about an easy way to lowercase URLs in EPiServer here. That works great for EPiServer CMS 6. For EPiServer 7 a couple of things has changed though.
Here’ an initialization module for lowercasing URLs for pages when they are created that works for EPiServer 7.
using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.Web; namespace MySite.Initialization { [ModuleDependency(typeof(EPiServer.Web.InitializationModule))] public class UrlSegmentHandlingInitialization : IInitializableModule { public void Initialize(InitializationEngine context) { UrlSegment.CreatedUrlSegment += UrlSegmentOnCreatedUrlSegment; } private void UrlSegmentOnCreatedUrlSegment( object sender, UrlSegmentEventArgs urlSegmentEventArgs) { var segment = urlSegmentEventArgs.RoutingSegment.RouteSegment .ToLowerInvariant(); urlSegmentEventArgs.RoutingSegment.RouteSegment = segment; } public void Uninitialize(InitializationEngine context) { UrlSegment.CreatedUrlSegment -= UrlSegmentOnCreatedUrlSegment; } public void Preload(string[] parameters) { } } }
Beyond lowercasing the URL segment we can of course also modify it in other ways should we want to.
For instance, if a page’s name contains a hyphen surrounded by whitespaces it will by default have a URL segment with three hyphens in a row (“---“). This can easily be fixed in the initialization module with code such as this:
while (segment.Contains("--")) { segment = segment.Replace("--", "-"); }
Lowercase existing URLs
In Lars post he shows how to update URLs for existing pages by modifying their URL segments in the database. That’s probably a preferable approach for sites with a lot of content with EPiServer 7 as well. For smaller sites however it could also be done through the API.
var contentRepository = ServiceLocator.Current .GetInstance<IContentRepository>(); var allPages = contentRepository .GetDescendents(ContentReference.RootPage) .Select(contentRepository.Get<IContent>) .OfType<PageData>(); foreach (var page in allPages) { var clone = page.CreateWritableClone(); var segment = clone.URLSegment.ToLowerInvariant(); clone.URLSegment = segment; contentRepository.Save( clone, SaveAction.Publish | SaveAction.ForceCurrentVersion, AccessLevel.NoAccess); }
PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.
My book
Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!
Comments
comments powered by Disqus