Linking to items in other sites gives a lot of problems and strange urls.
Sitecore creates links by using the context of the current site.
There is an easy solution for creating out of context links, just switch the context!

First we need to find the site context of the item. The Sitecore.Configuration.Factory gives us access to all available sites.

var sites = Sitecore.Configuration.Factory.GetSiteInfoList();

Now we need to find the corresponding site.

SiteContext siteContext  = null;
foreach (var site in sites)
{
    var fullPath = string.Concat(site.RootPath + site.StartItem);
    if (item.Paths.FullPath.StartsWith(fullPath))
    {
        siteContext = new SiteContext(site);
        break;
    }
}

Now that we’ve got the site context, we can generate the correct url.

var urlOptions = LinkManager.GetDefaultUrlOptions();
urlOptions.Site = siteContext;
var url = LinkManager.GetItemUrl(item, urlOptions);
The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)