Insights

How to Get Sitecore Context in a Web API Controller using Target Host Name

Use Target Host Name to Resolve Context

An often encountered issue in web APIs is that Sitecore has no context, or that it doesn't have the context you're expecting.

For more information about how to set up a web API and a few important factors to consider, see our post on how to register custom routes for APIs in Sitecore.



private SiteContext GetSiteContext()
{
	Sitecore.Web.SiteInfo currentSiteInfo = null;
	var siteInfoList = Sitecore.Configuration.Factory.GetSiteInfoList();
	var currentHostName = HttpContext.Current.Request.Url.Host;

	foreach (Sitecore.Web.SiteInfo siteInfo in siteInfoList)
	{
		if (siteInfo.TargetHostName.Equals(currentHostName))
		{
			currentSiteInfo = siteInfo;
		}
	}

	if (currentSiteInfo == null)
	{
		Sitecore.Diagnostics.Log.Error("Current site info not found -- exiting.", this);

		return null;
	}

	return Sitecore.Configuration.Factory.GetSite(currentSiteInfo.Name);
} 

Assuming your target host names are set up correctly for all upstream environments, this should work like a charm.

Good luck out there,

Marcel

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting