Search code examples
c#asp.net-core-mvcasp.net-core-6.0currentculture

CurrentUICulture determining wrong culture


TL;DR: .NET 6 is refusing to render MVC pages when the browser's language is set to zh-TW.   When my ASP.NET Core 6 MVC application renders a page, if the user has the browser language set to Chinese (Traditional) (zh-TW), it displays Chinese (Simplified) (zh-CN) and the CurrentCulture name is shown as zh.   I have the following language resource files:  

  • strings.zh-CHS.resx
  • strings.zh-CHT.resx
  • Strings.zh-cn.resx
  • strings.zh-Hans.resx
  • strings.zh-Hant.resx
  • Strings.zh-TW.resx
  • strings.zh.resx   (I have checked that the correct translations are in those files.)   In order to define which resource files should be used when performing language selection, my Configure method contains this code:  
CultureInfo[] allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
string location = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
var supportedCultures = allCultures.Where(c => (Directory.Exists(Path.Combine(location, c.Name)) || c.Name.StartsWith("zh-")) && c.LCID != 127).ToList();
 
// ***added here***
 
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-US"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});

  When debugging, the supportedCultures list includes the CultureInfo objects with these names:  

  • zh
  • zh-Hans
  • zh-Hant
  • zh-Hant-TW   In an effort to avoid the selection defaulting to the first matching language in the list, I have added this code to the ***added here*** line above:  
supportedCultures.Reverse();

  How do I get .net to recognise that the browser is requesting the zh-TW culture?


Solution

  • This is another ICU issue, as zh-TW is not an ISO standard name, AllCultures will not contain it, and zh-TW will not match zh-Hant-TW.

    I can find 2 solutions:

    1. Manually add zh-TW

      supportedCultures.Add(new CultureInfo("zh-TW"));
      
    2. Use NLS instead of ICU, https://stackoverflow.com/a/77192077/6196568