How to check whether Sitecore item is using alias

2019-02-14 03:50发布

问题:

Currently an "Alias" in Sitecore will produce multiple routes to the same content item which can negatively affect SEO in some cases.

I am looking for a way to programatically check whether the current Page/Item/URL/Request is using an alias or not.

I was hoping there would be something along the lines of:

Sitecore.Web.WebUtil.IsAlias

Any ideas on how to check for aliases?

-------UPDATE-------

Here is my current solution which appears to work just fine... Unless anyone has a better ideas?:

protected bool IsAlias
{
    get
    {
        string fullPath = LinkManager.GetItemUrl(Sitecore.Context.Item);
        return !HttpContext.Current.Request.RawUrl.StartsWith(fullPath, StringComparison.OrdinalIgnoreCase);
    }
}

------ UPDATE 2 ------

Here is a working solution based on Yan's suggestions. I don't believe Sitecore.Context.Database.Aliases.GetTargetUrl() is working as of Sitecore 6.4.1. so I had to improvise a little.

if (Sitecore.Configuration.Settings.AliasesActive &&
    Sitecore.Context.Database.Aliases.Exists(HttpContext.Current.Request.RawUrl))
{
    const string format = "<link rel=\"canonical\" href=\"{0}://{1}{2}\"/>";
    Item targetItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Database.Aliases.GetTargetID(HttpContext.Current.Request.RawUrl));
    return String.Format(format, HttpProtocol, HttpContext.Current.Request.Url.Host, LinkManager.GetItemUrl(targetItem));
}

回答1:

I would rely on the Context.Database.Aliases.Exists(path) in your case. Also, it seems to be a good idea to check whether the aliases are active in the web.config: Sitecore.Configuration.Settings.AliasesActive.



回答2:

What we have done in the past is when an alias is used to set a canonical url link in the head of the page.
For example if you have /food alias pointing to /news/food when you go to the /food you'll put <link href="http://[websiteurl]/news/food" rel="canonical" /> in the <head> of the page.

EDIT:

Here is another way

public class AliasResolver : Sitecore.Pipelines.HttpRequest.AliasResolver
{
    public override void Process(HttpRequestArgs args)
    {
        base.Process(args);

        if (Context.Item != null)
        {
            args.Context.Items["CanonicalUrl"] = Context.Item.GetFullUrl(args.Context.Request.Url);
        }
    }
}

Then in your header control all you need to do is check whether HttpContext.Current.Items["CanonicalUrl"] is set and display it.