0

I am using Sitecore 9.1.1 with SXA 1.8.1.

I am trying to generate the image URL with hash programmatically. I tried the following code but the HashingUtils does not seem to be working - the image URL is correct but the hash is not generated.

Media.RequestProtection.SharedSecret was set and the Request Protection is enabled. Using FieldRenderer for images generates the hash in other places on the website so I assume something is wrong with my code. Can you spot something?

ImageField imageField = item.Fields[fieldId];

            if (imageField != null && imageField.MediaItem != null)
            {
                var mediaSrc = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(imageField.MediaItem, new MediaUrlOptions { Language = Context.Language })) ?? string.Empty;
                var imageUrlWithHash = HashingUtils.ProtectAssetUrl(mediaSrc);

                return string.IsNullOrEmpty(mediaSrc) ? string.Empty : $"<img src=\"{imageUrlWithHash}\" />";
            }

As the output of this code I'm getting the URL without the hash:

<img src="/-/media/Project/myimagename.jpg">

Any ideas what could be causing that?

2
  • 1
    Try specifying a MaxWidth in your MediaUrlOptions. I don't believe Sitecore Media Hashing kicks in when just serving the raw file as-is from the Media Library. E.g. string imageUrl = HashingUtils.ProtectAssetUrl(MediaManager.GetMediaUrl(imageField.MediaItem, new MediaUrlOptions {MaxWidth = 1024})) – Mark Cassidy May 5 at 7:56
  • That did the job! Thank you so much @MarkCassidy! – 9_9 May 5 at 8:04
4

Media Request Protection only kicks in when it needs to. It is designed to prevent media specific parameters from being manipulated (e.g. specifying a MaxWidth for an image of 10248000, forcing Sitecore to fill its media cache with useless scaling of images).

Therefore if no parameter is present on your media url, no hashing is required. Sitecore will server the image as-is.

Adding for instance a MaxWidth limitation to your image url rendering (which would be a recommended practice in any event), Media Request Protection kicks in and generates a hash for your image.

Example: string imageUrl = HashingUtils.ProtectAssetUrl(MediaManager.GetMediaUrl(imageField.MediaItem, new MediaUrlOptions {MaxWidth = 1024}))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.