Sitecore get Context from fully qualified URL

One of the basic Sitecore concepts is the concept of a context. The context is resolved from the HTTP Context to Sitecore and determines the database, language, user domain, content start item etc. The context is defined in the App_Config/Sitecore.config configuration file in the <sites> section:

  <site name="shell" ... rootPath="/sitecore/content" startItem="/home" language="en" contentLanguage="en" database="core" domain="sitecore" ... />
  <site name="website_en" ... hostName="||" language="en" database="web" domain="extranet" ... />
  <site name="website_da" ... hostName="" language="da" database="web" domain="extranet" ... />

The context is resolved from a first-match algorithm where Sitecore goes through the list of sites and finds the first site that matches the criteria.

You can go through the sites list yourself using the Sitecore.Configuration.Factory.GetSiteInfoList() method. So with a little guesswork you can get the context from any URL, assuming that:

  • The url must be fully qualified (i.e.
  • The site section contains the URL in the hostName property
using Sitecore.Configuration;
using Sitecore.Sites;
using Sitecore.Web;

public static SiteContext GetSiteContext(Uri url)
  string hostName = url.Host;

  foreach (SiteInfo site in Factory.GetSiteInfoList())
    foreach(string sitecoreHostName in site.HostName.Split('|'))
      if (string.Equals(sitecoreHostName, hostName, StringComparison.InvariantCultureIgnoreCase))
        return new SiteContext(site);

  return null;

WHAT IS THE HostName VS TargetHostName?

Sitecore uses 2 definitions to determine URL’s:

  • The hostName is the incoming URL. You can define a list of incoming URL’s in a pipe separated list, and each URL will be resolved to that site context.
  • The targetHostName is the outgoing URL and determines which URL to create when asking for a fully qualified 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 .net, c#, General .NET, Sitecore 6, Sitecore 7, Sitecore 8, Sitecore 9 and tagged , , , . Bookmark the permalink.

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.