AlexTeixeira / Askmethat-Aspnet-JsonLocalizer

Json Localizer library for .NetStandard and .NetCore Asp.net projects
MIT License
91 stars 29 forks source link

WithCulture is non working is no #135

Open imperugo opened 2 years ago

imperugo commented 2 years ago

Hi, as far as I understood, if I want to change the culture to use in order to retrieve the localized string I have to use the WithCulture extension method in this way (I've used the Askmethat.Aspnet.JsonLocalizer.Sample.I18nTest example):

public WeatherForecastService(IJsonStringLocalizer localizer)
{
    _localizer = localizer.WithCulture(new CultureInfo("fr-FR"));
    _summaries.Add(_localizer.GetString("Freezing"));
    _summaries.Add(_localizer.GetString("Bracing"));
    _summaries.Add(_localizer.GetString("Chilly"));
    _summaries.Add(_localizer.GetString("Cool"));
    _summaries.Add(_localizer.GetString("Mild"));
    _summaries.Add(_localizer.GetString("Warm"));
}

Unfortunately this method is always return the request culture or default instead of fr-FR that is supported:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "JsonLocalizationOptions": {
    "ResourcesPath": "i18n",
    "AdditionalResourcePaths": [ "common_i18n" ],
    "CacheDuration": "00:00:15",
    "DefaultCulture": "pt-PT",
    "DefaultUICulture": "pt-PT",
    "SupportedCultureInfos": [ "en-US", "fr-FR", "pt-PT" ],
    "IsAbsolutePath": true,
    "FileEncodingName": "utf-8",
    "UseBaseName": false
  }
}

Looking the code the implementation of GetString, it is correctly based on CultureInfo.CurrentUICulture but the WithCulture is working on CultureInfo.CurrentCulture:

public IStringLocalizer WithCulture(CultureInfo culture)
{
    if (!_localizationOptions.Value.SupportedCultureInfos.Contains(culture))
    {
        _localizationOptions.Value.SupportedCultureInfos.Add(culture);
    }

    CultureInfo.CurrentCulture = culture;

    return new JsonStringLocalizer(_localizationOptions, _env);
}

Am I wrong or the WithCulture is buggy? In case of no, what's the correct way to retrieve a localized string on a specific culture that is different from the current?

Thanks