Sitecore get host name from a different context

Ohno, you are running in one context, say the “shell” context, and all of your URL’s have to point to the “website” context. The hustler will obviously hard-code the domain name of the “website” into the code. But the Sitecore aficionado will check the SiteContext and retrieve the “TargetHostName” property.

This tiny class will qualify your relative URL’s to absolute URL’s, matching the domain name as specified in the <sites> section of your configuration (code simplified for readability, you should apply your own exception handling):

using System;
using System.Web;
using Sitecore.Sites;

namespace MyNameSpace
  internal static class FullyQualifiedUrlService
    public static string Qualify(string relativeUrl, string sitename)
      SiteContext sitecontext = SiteContext.GetSite(sitename);
      return Qualify(relativeUrl, sitecontext);

    public static string Qualify(string relativeUrl, SiteContext sitecontext)
      if (!relativeUrl.StartsWith("/"))
        relativeUrl = relativeUrl + "/";
      return string.Format("{0}://{1}{2}", sitecontext.SiteInfo.Scheme, sitecontext.TargetHostName, relativeUrl);


Imagine this is your sites definition for the “website” context:

  <site name="website" targetHostName="" hostName="|" scheme="http" ... .../>

The class is called using the following code:

string relativeUrl = "/this/is/my/page";
string absoluteUrl = FullyQualifiedUrlService.Qualify(relativeUrl, "website");

And will return the following result:

Both the scheme and the targetHostName is resolved from the context using the Scheme and TargetHostName properties of the SiteContext.

Sitecore uses 2 properties for host resolving:

  • The “hostName” can be a pipe-separated list of domains and is used to target the number of possible URL’s that points to this context.
  • The “targetHostName” is one URL which is used internally to resolve and fully qualify your URL.




About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in c#, General .NET, Sitecore 6, Sitecore 7, Sitecore 8 and tagged , , , . Bookmark the permalink.

2 Responses to Sitecore get host name from a different context

  1. Pingback: Sitecore get Context from fully qualified URL | Brian Pedersen's Sitecore and .NET Blog

  2. Pingback: Which of my old Sitecore posts are still valid in Sitecore 9? | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.