Asp.net core localization Is there any way to allow all cultures?
Asked Answered
S

1

8

I want to allow all cultures in my application. As you can see below, I'm allowing few cultures. And I'm having a custom provider that will get the user's culture. If his culture isn't in the SupportedCultures that means I can't handle his culture (even if I can). I can't know before assigning the SupportedCultures what cultures will be supported.

E.g. GetTheUserCulture() returns "de". When I'll try later to have the culture, it will fallback to the default language ("en" in this case). Or I want it to be "de".

Is there a way to Allow all cultures ?

            const string defaultCulture = "en";
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo(defaultCulture),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr"),
                    new CultureInfo("es"),
                    new CultureInfo("ru"),
                    new CultureInfo("ja"),
                    new CultureInfo("ar"),
                    new CultureInfo("zh"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("en-UK")
                };

                options.DefaultRequestCulture = new RequestCulture(defaultCulture);
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
                {
                    return new ProviderCultureResult(GetTheUserCulture());
                }));
            });
Schulman answered 4/2, 2020 at 16:0 Comment(0)
S
14

We can retrieve all cultures with CultureInfo and then add it to the SupportedCultures. It will look like that :

            services.Configure<RequestLocalizationOptions>(options =>
            {
                CultureInfo[] supportedCultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures)
                    .Where(cul => !String.IsNullOrEmpty(cul.Name))
                    .ToArray();

                options.DefaultRequestCulture = new RequestCulture(defaultCulture);
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            }
Schulman answered 4/2, 2020 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.