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:
<sites> <site name="shell" ... rootPath="/sitecore/content" startItem="/home" language="en" contentLanguage="en" database="core" domain="sitecore" ... /> ... <site name="website_en" ... hostName="www.site.com|www.site.eu|www.site.co.uk" language="en" database="web" domain="extranet" ... /> <site name="website_da" ... hostName="www.site.dk" language="da" database="web" domain="extranet" ... /> </sites>
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. https://www.site.com/url)
- 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.
MORE TO READ:
- The Sitecore Context from Sitecore
- Sitecore get host name from a different context by briancaos
- How to get the domain name for a Sitecore item from stackoverflow