Search code examples
.net-corelocalizationglobalization

.NET Core localization globalization


Can someone confirm for me whether this code changes the culture for all users of the application, or just for the current user?

var cultureInfo = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

I want to show a combo with the different cultures accepted for the application and change the culture when I select it in the combo, but if I open the application in, for example Chrome and Firefox when I change in one, it seems that the culture changes in the other, and this is scary.


Solution

  • you can use bellow code

    Startup.ConfigureServices

    CultureInfo[] supportedCultures = new[]
           {
            new CultureInfo("ar"),
            new CultureInfo("fa"),
            new CultureInfo("en")
        };
    
        services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new RequestCulture("ar");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            options.RequestCultureProviders = new List<IRequestCultureProvider>
                {
                    new QueryStringRequestCultureProvider(),
                    new CookieRequestCultureProvider()
                };
    
        });
    

    Startup.Configure

    app.UseRequestLocalization();
    

    change language:

    [HttpPost]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new     RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );
    
        return LocalRedirect(returnUrl);
    }
    

    More Details: here