Sitecore.StringUtil.EnsurePrefix on GetMediaUrl with alwaysIncludeServerUrl=”true” will break the code on Sitecore7.xx

Recently (I guess on SC 7) Sitecore changed the behavior of  alwaysIncludeServerUrl so that it can also be used by Media item URL.

Now, if you set alwaysIncludeServerUrl=”true”  and in the code as we have been advised to use EnsurePrefix(‘/’ then the URLs for Media will look like this “/http:www.xxx.com/~/Media/blahblah”  so it adds a leading slash.

I can use <setting name=Media.AlwaysIncludeServerUrl value=/> to tell it not to create absolute URLs  for media and then I don’t have to find every reference to EnsurePrefix and remove it but then I will not have absolute URLs for Media Items.

Anyways to make the story short, I created my own EnsurePrefix  (see below) and replaced every single Sitecore.StringUtil.EnsurePrefix in the code but unfortunately MediaManager does not have a  GetDefaultUrlOptions so I had to use the LinkManager.GetDefaultUrlOptions().AlwaysIncludeServerUrl instead which is wrong because it does not indicates if Media.AlwaysIncludeServerUrl is set.

/// <summary>
/// Ensures the prefix for media link.
/// </summary>
/// <param name=”prefix”>The prefix.</param>
/// <param name=”value”>The value.</param>
/// <returns></returns>
public static string EnsurePrefixForMediaLink(char prefix, string value)
{
   if (string.IsNullOrEmpty(value))
return prefix.ToString(CultureInfo.InvariantCulture);
if (!LinkManager.GetDefaultUrlOptions().AlwaysIncludeServerUrl)
   {
     if (value[0] == prefix)
     return value;
     return prefix + value;
    }
   return value;
  }
Advertisement

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 )

Facebook photo

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

Connecting to %s