The reason why I want to change the domain of an image url is because I'm providing an API to a third party. And the regulation is all media url and internal link url, needs to replace the default domain to a specific one.

I know that by setting Options.AlwaysIncludeServerUrl = true, the result of MediaManager.GetMediaUrl() will response an absolute path url with domain.

However the domain I got is not what I want, the image url is something like:


I want it be a specific site hostname, which the site is setted in config file. So I decide to switch siteContext before getMediaUrl()

string GetImageItemUrl(Item item, ID templateId)
    string src = string.Empty;
    ImageField imageField = item.Fields[templateId];
    if (imageField != null && imageField.MediaItem != null)
        var site = Sitecore.Configuration.Factory.GetSite("xxxSite");
        using (new SiteContextSwitcher(site))
            var image = new MediaItem(imageField.MediaItem);
            MediaUrlOptions mediaUrlOptions = new MediaUrlOptions();
            mediaUrlOptions.AlwaysIncludeServerUrl = true;
            mediaUrlOptions.AbsolutePath = true;
            src = MediaManager.GetMediaUrl(image, mediaUrlOptions);
    return src;

I also patched a config, here is the site section in file App_Config/include/projectname/z.projectname.Dev.Settings.config

        <site name="xxxSite">
            <patch:attribute name="database">master</patch:attribute>
            <patch:attribute name="hostName">test.xxxxxx.com</patch:attribute>
            <patch:attribute name="targetHostName">test.xxxxxx.com</patch:attribute>

But the result is the same as before. Not the https://test.xxxxxx.com/-/media/view-explorer/presets/delux-128x128.jpg as I expected.

So am I using it the right way?

(Updated: It's 8.2 I'm using)

  • Which Sitecore version do you use? Jun 12 '20 at 10:17
  • Did you try to set the URL via mediaUrlOptions.MediaLinkServerUrl? Jun 17 '20 at 8:35

Your Answer

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

Browse other questions tagged or ask your own question.