Resolving the SiteContext by URL

Reason

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.

Code

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("?", ".") + "$";
}

Example

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

3 thoughts on “Resolving the SiteContext by URL

  1. Nice and useful post.

    I guess you would be able to use the WildCardParser class from the Sitecore API instead of the regex. I started writing a post about this class and how to use it to resolve a SiteContext by item, I just realized that I never published the post. Will post it later today or tomorrow 🙂

  2. Pingback: Matching Wildcards in Sitecore - Laub plus Co

  3. Pingback: Sitecore get host name from a different context | Brian Pedersen's Sitecore and .NET Blog

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s