Ohno, you are running in one context, say the “shell” context, and all of your URL’s have to point to the “website” context. The hustler will obviously hard-code the domain name of the “website” into the code. But the Sitecore aficionado will check the SiteContext and retrieve the “TargetHostName” property.
This tiny class will qualify your relative URL’s to absolute URL’s, matching the domain name as specified in the <sites> section of your configuration (code simplified for readability, you should apply your own exception handling):
using System; using System.Web; using Sitecore.Sites; namespace MyNameSpace { internal static class FullyQualifiedUrlService { public static string Qualify(string relativeUrl, string sitename) { SiteContext sitecontext = SiteContext.GetSite(sitename); return Qualify(relativeUrl, sitecontext); } public static string Qualify(string relativeUrl, SiteContext sitecontext) { if (!relativeUrl.StartsWith("/")) relativeUrl = relativeUrl + "/"; return string.Format("{0}://{1}{2}", sitecontext.SiteInfo.Scheme, sitecontext.TargetHostName, relativeUrl); } } }
USAGE:
Imagine this is your sites definition for the “website” context:
<sites> ... <site name="website" targetHostName="www.mysite.com" hostName="mysite.com|www.mysite.com" scheme="http" ... .../> ... </sites>
The class is called using the following code:
string relativeUrl = "/this/is/my/page"; string absoluteUrl = FullyQualifiedUrlService.Qualify(relativeUrl, "website");
And will return the following result:
Both the scheme and the targetHostName is resolved from the context using the Scheme and TargetHostName properties of the SiteContext.
Sitecore uses 2 properties for host resolving:
- The “hostName” can be a pipe-separated list of domains and is used to target the number of possible URL’s that points to this context.
- The “targetHostName” is one URL which is used internally to resolve and fully qualify your URL.
MORE TO READ:
- Resolving the SiteContext by URL by Reason->Code->Example
- Sitecore, SiteContext and Context.Database, oh my! by Søren Engel
- Correctly switching Sitecore contextes by ctor.io
