Skip to content

Instantly share code, notes, and snippets.

@jammykam
Last active March 5, 2024 17:11
Show Gist options
  • Save jammykam/c89e2f4eb62638226e1d005d22802f0a to your computer and use it in GitHub Desktop.
Save jammykam/c89e2f4eb62638226e1d005d22802f0a to your computer and use it in GitHub Desktop.
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