Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Sitecore Media Request handler to deal with media items with the same name but different extensions. If the media with matching extension is not found then the default Sitecore behaviour is used. This is directly inspired by the post by Martin Davies: http://sitecoreskills.blogspot.co.uk/2014/01/handling-duplicate-media-paths-in.html
using System.Web;
using Sitecore.Diagnostics;
using Sitecore.Resources.Media;
using System;
using System.Linq;
using Sitecore.Data.Items;
using Sitecore.IO;
namespace MyProject.Custom.Media
{
public class MediaRequestHandler : Sitecore.Resources.Media.MediaRequestHandler
{
protected override bool DoProcessRequest(HttpContext context, MediaRequest request,
Sitecore.Resources.Media.Media media)
{
Assert.ArgumentNotNull((object) context, "context");
Assert.ArgumentNotNull((object) request, "request");
Assert.ArgumentNotNull((object) media, "media");
string requestExtension = FileUtil.GetExtension(context.Request.FilePath);
// if the extension does not match then try to find the alternate
if (!string.Equals(media.Extension, requestExtension, StringComparison.InvariantCultureIgnoreCase))
{
// try to find a matching sibling of same name
Item requestItem = media.MediaData.MediaItem;
var alternateItem = requestItem.Database.SelectItems(requestItem.Paths.FullPath)
.FirstOrDefault(i => i["Extension"] == requestExtension);
if (alternateItem != null)
media = MediaManager.GetMedia(alternateItem);
}
return base.DoProcessRequest(context, request, media);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.