10.0
  1. Working with links

Access the friendly URL of a media item

You can use the Sitecore.Resources.Media.MediaManager.GetMediaUrl() method to access the friendly URL of a media item. For example, to access the friendly URL of the media item /Sitecore/Media Library/Images/Sample in the Master database:


Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item sampleItem = master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.Item sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);

string url = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(sampleMedia));
Warning

Sitecore does not automatically include the leading slash character (“/”) in media URLs. This results in relative URLs for media items, which IIS resolves to the document root due to the tilde character (“~”). In solutions with very deep information architectures, relative media URLs can exceed limits imposed by the Web client or the Web server. Use the Sitecore.StringUtil.EnsurePrefix() method as shown in the previous example to ensure media URLs include the leading slash character.

When you use an IIS internal URL rewrite to rewrite a URL to a Sitecore Media Library URL, Sitecore media resolution evaluates the original request path. If the original request path does not contain the configured media prefix, Sitecore does not recognise the request as a media request and returns a 404 response. This is expected behaviour for Sitecore media-item resolution and does not indicate a problem with IIS URL Rewrite.

A redirect behaves differently because the browser makes a new request to the Media Library URL using the proper media URL prefixes. Sitecore therefore receives the Media Library path and can resolve the media item.

If you need to expose a media item through a clean URL without exposing the Media Library path, consider using a Sitecore alias. If the required URL cannot be represented by an alias, a custom implementation might be required.

You can use the Sitecore.Links.UrlBuilders.MediaUrlBuilderOptions class to specify media options. For example, to retrieve the URL of the thumbnail of the /Sitecore/Media Library/Images/Sample media item in the Master database:


Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item sampleItem = master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.MediaItem sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);

Sitecore.Links.UrlBuilders.MediaUrlBuilderOptions mediaOptions = new Sitecore.Links.UrlBuilders.MediaUrlBuilderOptions();
mediaOptions.Thumbnail = true;

string url = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(sampleMedia, mediaOptions));
If you have suggestions for improving this article, let us know!