sitecore

Sitecore LinkManager.GetItemUrl() resolving to alias


I've created aliases for the home page of one of the local sites (and its child pages) in my national website - and I can't figure out how this is happening.

When someone lands on a local page, I have a control (cs file) that creates the local links (to the child pages) on the left hand side of the local web page. These links are derived from the Sitecore context (current item's content path).

After I created the aliases for all of the pages in a local site, that's when I noticed this problem. If the URL is a Sitecore alias, the navigational links are built for the child aliases - otherwise they are resolved by the Sitecore LinkManager, just as they were before the aliases were created. However, when I hit a page for the original local item (not the alias), the links are being rendered for the alias:

childLink.NavigateUrl = LinkManager.GetItemUrl(child);

And I've verified that the child item is valid. Does anyone have any suggestions as to why the LinkManager would be rendering the links for the aliases - and how this can be avoided?


Solution

  • Sitecore.Links.LinkManager.GetItemUrl(item) returns the path to the original item, not the alias path. If you have special logic to identify aliases, for example by using the Sitecore.Context.RawUrl property, you may be running into an issue with output caching, which could be causing the alias version of the control to be displayed when you navigate to the original item.

    Update: I'm pretty sure you are running into an output caching issue. I was able to reproduce this behavior by creating a test control, which displays a timestamp and the RawUrl, and by turning on output caching for the control in Presentation Details.

    The first time the control is displayed, whether it is for the item or the alias, the output is cached, and this cached output is displayed each time the control is viewed, either for the original item or the alias. Even if you switch on "Vary By Data", the effect is the same, because "Vary By Data" is driven by the Data Source item, not the URL.

    To fix this behavior, you need to add the cached state to the output of the GetCachingId property:

    protected override string GetCachingID()
    {
        return this.GetType().Name + (IsAlias() ? "Alias": "Item");
    }
    
    private bool IsAlias()
    {
        return Sitecore.Context.Database.Aliases.Exists(Sitecore.Context.RawUrl);
    }
    

    Props to this answer for the IsAlias logic.