Resolving the SiteContext by URL


Sometimes it’s useful to resolve the SiteContext matching a given URL manually, e.g. when you don’t want to change the current site context by using the standard Sitecore.Pipelines.HttpRequest.SiteResolver, or when working in a part of a solution where site context resolving isn’t handled by the Sitecore httpRequestBegin-pipeline.

Since Sitecore allows the use of wildcards in the hostName and targetHostName of any configured site, matching a URL to the appropriate SiteContext sometimes takes more than just doing a simple string comparison.


In the code shown below the site context “website” is used as a fallback if no other match can be found – consider whether or not this makes sense in your use case.

using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Sites;
using Sitecore.Web;
using System;
using System.Text.RegularExpressions;

public static SiteContext GetSiteContext(Uri requestUrl)
  Assert.ArgumentNotNull(requestUrl, "requestUrl");
  string requestHostName = requestUrl.Host;
  foreach (SiteInfo siteInfo in Factory.GetSiteInfoList())
    if (IsMatch(requestHostName, siteInfo.HostName) || IsMatch(requestHostName, siteInfo.TargetHostName))
      return new SiteContext(siteInfo);
  return SiteContext.GetSite("website");

private static bool IsMatch(string input, string wildcardPattern)
  if (string.IsNullOrWhiteSpace(input))
    return false;
  if (string.IsNullOrWhiteSpace(wildcardPattern))
    return false;
  string regexPattern = WildcardToRegex(wildcardPattern);
  return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase);

private static string WildcardToRegex(string pattern)
  return "^" + Regex.Escape(pattern).Replace("*", ".*").Replace("?", ".") + "$";


The screenshot shown below shows a match being made for a site which is configured with an asterisk in it’s hostName:

Resolve the Sitecore SiteContext by URL