Overriding Sitcore’s Media Handler

A while back, I completed a multi-site, multi-lingual Sitecore 7/AspDotNetStorefront implementation.

Each site sells digital content such as Research Papers, Protocols, Webinars Videos. A customer can also purchase a subscription. All the products are stored in Sitecore’s Media Library. I needed a way to prevent access to these items if multiple business rules were not met. The solution is rather basic.

namespace Company.Sitecore.Library.Handlers
{
    using System;
    using System.Web;
    using Sitecore.Resources.Media;

    public class MediaAccess : MediaRequestHandler
    {
        public override void ProcessRequest(HttpContext context)
        {
            var site = Sitecore.Context.Site;

            if (site != null || site.Name.Equals("shell", StringComparison.InvariantCultureIgnoreCase))
            {
                var mediaRequest = MediaManager.ParseMediaRequest(context.Request);
               
                if (mediaRequest != null)
                {
                    var media = MediaManager.GetMedia(mediaRequest.MediaUri);

                    if (media != null)
                    {
                        var mediaItem = media.MediaData.MediaItem;

                        // Determine if the user is authenticated and has the correct role for the media item
                        // Determine if the user has purchased the media item or has active subscription
                        // If business rules not met redirect to an Access Denied page.
                        // Else fall through to base.ProcessRequest(context);
                    }
                }
            }

            base.ProcessRequest(context);
        }
    }
}

 

Edit the Web.config

<system.webServer>
<handlers>
// Replace
<add verb=”*” path=”sitecore_media.ashx” type=”Sitecore.Resources.Media.MediaRequestHandler, Sitecore.Kernel” name=”Sitecore.MediaRequestHandler” />

// With
<add verb=”*” path=”sitecore_media.ashx” type=”Company.Sitecore.Library.Handlers.MediaAccess, Company.Library” name=”Sitecore.MediaRequestHandler”/>.

// And
<system.web>
<httphandlers>

// Replace
<add verb=”*” path=”sitecore_media.ashx” type=”Sitecore.Resources.Media.MediaRequestHandler, Sitecore.Kernel” />

// With
<add verb=”*” path=”sitecore_media.ashx” type=”Company.Library.Handlers.MediaAccess, Company.Library”/>