Sitecore 8: Media URL in Index

I have recently encountered a situation where I needed to index some media items. I am working on a Sitecore 8.2 solution and I have a simple custom web index on SOLR in which the media URL is a computed field. My code for the computed field was as simple as this:

public object ComputeFieldValue(IIndexable indexable)
{
  var item = (Item)(indexable as SitecoreIndexableItem);
  if (item == null)
  {
    return null;
  }

  return MediaManager.GetMediaUrl(item, mediaUrlOptions);
}

However, the results were a bit strange. Some of the index records had in media URL values that began with “/sitecore/shell”. After a bit of research, I found some explanation in this issue on StackOverflow: http://stackoverflow.com/questions/27272832/urllink-in-sitecore-indexs-returns-media-url-with-sitecore-shell-media. In my case the indexing was done from the Indexing Manager, but I still got these mixed results in terms of URLs, where some were relative and some were starting with “/sitecore/shell”. I also checked the Url field which should have been computed automatically in the Sitecore index, but in my case it was always null, so it was not an option. Maybe, as mentioned in the given Sitecore answer to the issue on StackOverflow, they did give up on computing this field for media items.

I followed the advice from the issue and computed all the URLs with Absolute Path set to false:

public object ComputeFieldValue(IIndexable indexable)
{
  var item = (Item)(indexable as SitecoreIndexableItem);
  if (item == null)
  {
    return null;
  }

  var mediaUrlOptions = new MediaUrlOptions
  {
    AbsolutePath = false
  };

  return MediaManager.GetMediaUrl(item, mediaUrlOptions);
}

With the above code, all the media URLs were created correctly, starting with “-/media/”. And when rendering the value of the media URL in an <a href=”@item.MediaUrl“> tag, which was the intended purpose, the media item could be properly downloaded.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s