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

Use Target Host Name to Resolve Context

December 13, 2018

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](https://getfishtank.ca/en/blog/how-to-register-custom-routes-in-sitecore-9-helix).


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