Replace white space in media URLs in Sitecore

When the users create media items and media folders in Sitecore that contain white space all media URLs will also contain white spaces. This is apparently frowned upon by W3C and their html-validator.

One would think that the normal <encodeNameReplacements> in web.config also handles media URLs, but it does not. It is however realtively simple to override the GetMediaUrl(…) that Sitecore uses without being too intrusive.

Create your CustomMediaProvider class and base it on the normal MediaProvider class and override the GetMediaUrl(Sitecore.Data.Items.MediaItem item, Sitecore.Resources.Media.MediaUrlOptions options) function. Use the base class to do all the work and substitute the white spaces with %20.

namespace MyAssembly.MyNamespace
{
    public class CustomMediaProvider : Sitecore.Resources.Media.MediaProvider
    {
        public override string GetMediaUrl(Sitecore.Data.Items.MediaItem item, Sitecore.Resources.Media.MediaUrlOptions options)
        {
            var returnUrl = base.GetMediaUrl(item, options);
            return returnUrl.Replace(" ", "%20");
        }
    }
}

Then all there is left to do is substitute the standard media provider in web.config.

<mediaLibrary>
    <!-- MEDIA PROVIDER
    The media provider used to generate URLs, create media items, control media caching, parse media requests, and other media related functionality.      
    -->
    <mediaProvider type="MyAssembly.MyNamespace.CustomMediaProvider, MyAssembly" />

One thought on “Replace white space in media URLs in Sitecore

Leave a Reply

Your email address will not be published. Required fields are marked *