多语言网站中的 Sitecore 语言嵌入

S.K*_*S.K 0 asp.net sitecore

我在 Sitecore 中有一个多语言应用程序。默认语言是“en”。要求是“en”不应显示在 URL 中。我可以在这里使用语言嵌入“从不”,但它会导致其他语言出现问题。

jam*_*kam 6

为自己创建一个新的 LinkProvider 并options.LanguageEmbedding = LanguageEmbedding.Never仅设置为“en”,然后所有其他语言将使用您配置中设置的任何内容:

public class LinkProvider : Sitecore.Links.LinkProvider
{
    private static readonly Language neverEmbeddedLanguage = Language.Parse("en");

    public override string GetItemUrl(Item item, UrlOptions options)
    {
        if (item.Language == neverEmbeddedLanguage)
        {
            options.LanguageEmbedding = LanguageEmbedding.Never;
        }
        return base.GetItemUrl(item, options);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将您的新 LinkProvider 注册为默认的(使用补丁包含文件):

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <linkManager>
      <patch:attribute name="defaultProvider">custom</patch:attribute>
      <providers>
        <add name="custom" 
             type="MyProject.Custom.Links.LinkProvider, MyProject.Custom" languageEmbedding="always" ... />
      </providers>
    </linkManager>
  </sitecore>
</configuration>
Run Code Online (Sandbox Code Playgroud)

编辑:

正如 RvanDylan 正确指出的那样,我们还需要处理传入的请求,因为我们对特定语言禁用了语言嵌入。默认情况下,如果传递的 url 或 sc_lang 参数中没有嵌入语言代码,Sitecore 将回退到使用语言 cookie。因此,如果用户访问了一个 url,“/fr/contact”并访问了“/contact”,那么默认情况下他们将获得法语内容。我们需要处理这个问题并告诉 Sitecore 空实际上意味着英语。我们可以通过覆盖管道中StripLanguage处理器中的逻辑来做到这一点preprocessRequest

using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Pipelines.PreprocessRequest;
using Sitecore.Web;

namespace MyProject.Custom.Pipelines.preprocessRequest
{
    public class StripLanguage : Sitecore.Pipelines.PreprocessRequest.StripLanguage
    {
        private static readonly Language defaultLanguage = Language.Parse("en");

        public override void Process(PreprocessRequestArgs args)
        {
            Assert.ArgumentNotNull((object)args, "args");           
            string language = WebUtil.ExtractLanguageName(args.Context.Request.FilePath);

            if (string.IsNullOrEmpty(language))
            {
                Sitecore.Context.Language = defaultLanguage;
                Sitecore.Context.Data.FilePathLanguage = defaultLanguage;
                return;
            }

            base.Process(args);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以及与之相关的补丁配置文件:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <preprocessRequest>
        <processor type="MyProject.Custom.Pipelines.preprocessRequest.StripLanguage, MyProject.Custom" 
                   patch:instead="processor[@type='Sitecore.Pipelines.PreprocessRequest.StripLanguage, Sitecore.Kernel']" />
      </preprocessRequest>
    </pipelines>
  </sitecore>
</configuration>
Run Code Online (Sandbox Code Playgroud)