2014-11-04 92 views

回答

5

我找到關於"Browser Language Detection is Sitecore" from Mark Stiles的文章,但它不完全是我想要的,因爲他完全覆蓋了原生功能。

幾個小時後,我創建了自己的(也有Mark's代碼的部分)LanguageResolver用於檢測瀏覽器語言重定向,如果需要,並排除機器人。

public class LanguageResolver : Sitecore.Pipelines.HttpRequest.LanguageResolver 
{ 
    public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args) 
    { 
     Assert.ArgumentNotNull(args, "args"); 
     Language lang = GetLanguageFromBrowser(args); 
     if (lang != null) 
     { 
      Sitecore.Context.Language = lang; 
      // if current language doesn't match with default site language, it will do a redirect 
      if (Sitecore.Context.Language.Name != Sitecore.Context.Site.Language) 
      { 
       // do redirect 
       UriBuilder uriBuilder = new UriBuilder(args.Context.Request.Url); 
       uriBuilder.Path = Sitecore.Context.Language.Name + "/"; 
       HttpContext.Current.Response.Redirect(uriBuilder.Uri.ToString(), true); 
       args.AbortPipeline(); 
      } 
     } 
     else 
     { 
      base.Process(args); 
     } 
    } 
    /// <summary> 
    /// Gets language from browser but only when language cookie doesn't exist yet and URL is related to homepage 
    /// Logic taken from https://markstiles.net/Blog/2013/04/01/browser-language-detection-in-sitecore.aspx 
    /// </summary> 
    /// <param name="args"></param> 
    /// <returns></returns> 
    public Language GetLanguageFromBrowser(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args) 
    { 
     // site must be inicialized, language si resolved only for homepage and a site must have in its configuration resolveBrowserLang="true" ! 
     if (IsBrowserLangDetectionAllowed(args)) 
     { 
      // default site language 
      Language defaultLangPrefix = LanguageManager.GetLanguage(Sitecore.Context.Site.Language); 
      // gets browser languages 
      string[] userLangs = args.Context.Request.UserLanguages; 
      if (userLangs != null && userLangs.Any()) 
      { 
       foreach (string userLang in userLangs) 
       { 
        // gets first part where information about language is stored 
        string lang = userLang.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); 
        if (!String.IsNullOrEmpty(lang)) 
        { 
         Language scLang; 
         // if lang starts with the same letters as are in defaultLangPrefix 
         if (defaultLangPrefix != null && lang.StartsWith(defaultLangPrefix.CultureInfo.TwoLetterISOLanguageName)) 
         { 
          scLang = defaultLangPrefix; 
         } 
         else 
         { 
          if (!Language.TryParse(lang, out scLang)) 
          { 
           continue; 
          } 
         } 
         // then try to get the language item id from the language or two letter iso code 
         ID scLangId = LanguageManager.GetLanguageItemId(scLang, Sitecore.Context.Database); 
         if (ID.IsNullOrEmpty(scLangId)) 
         { 
          //sometimes the language found is slightly different than official language item used in SC 
          scLang = LanguageManager.GetLanguage(scLang.CultureInfo.TwoLetterISOLanguageName); 
          scLangId = LanguageManager.GetLanguageItemId(scLang, Sitecore.Context.Database); 
         } 
         if (ID.IsNullOrEmpty(scLangId)) 
         { 
          continue; 
         } 
         Item startItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath, scLang); 
         //if you've got a version in this language then use that language 
         if (startItem != null && startItem.Versions.Count > 0) 
         { 
          return scLang; 
         } 
        } 
       } 
       // fallback language from site configuration 
       return LanguageManager.GetLanguage(Sitecore.Context.Site.Properties["resolveBrowserFallbackLang"]); 
      } 
     } 
     return null; 
    } 
    /// <summary> 
    /// Determinates if detection is allowed 
    /// </summary> 
    /// <param name="args"></param> 
    /// <returns></returns> 
    protected bool IsBrowserLangDetectionAllowed(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args) 
    { 
     // site must be defined 
     return Sitecore.Context.Site != null 
      // lang cookie is not already set 
      && !args.Context.Request.Cookies.AllKeys.Contains(Sitecore.Context.Site.GetCookieKey("lang")) 
      // URL is related to homepage 
      && args.Context.Request.Url.AbsolutePath == "/" 
      // site must have property resolveBrowserLang="true" 
      && Sitecore.Context.Site.Properties["resolveBrowserLang"] == "true" 
      // user agent is not robot 
      && !Sitecore.Analytics.Configuration.AnalyticsSettings.Robots.ExcludeList.ContainsUserAgent(args.Context.Request.UserAgent); 
    } 
} 

客戶端的請求只適用於主頁,因此腳本可以擴展。

+0

你可以通過點擊「打勾」來「接受」你自己的答案。這將它從StackOverflow中未解決的問題列表中移除。 – 2015-06-01 19:48:53

+0

更新後的鏈接[]來自Mark Stiles的[「Browser Language Detection is Sitecore」](https://markstiles.net/blog/2013/4/1/browser-language-detection-in-sitecore/) https:// markstiles.net/blog/2013/4/1/browser-language-detection-in-sitecore/ – Annagram 2018-02-14 17:18:18