Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core : UseRequestLocalization why do we need to specify a list of supported cultures?

My goal is to use the browser language as the culture used in my controllers / views.

I found out about app.UseRequestLocalization() but just by itself it won't work, it only accept the current server culture. It needs options to add a list of supported culture for it to work:

app.UseRequestLocalization(options =>
{
    var supportedCultures = new string[] { "en-US", "en-CA", "fr-CA", "fr-FR" };
    options.AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures)
        .SetDefaultCulture("en-US");
});

This way, my browser sends fr-FR in the accept-language header, and the request comes to my ASP.NET Core controller correctly under the Thread.CurrentCulture property.

My question is, how to accept all cultures? Why do we need to supply a list of "supported" ones?

I understand localization dictionaries are only translated in your project for a certain list of cultures. But when it doesn't it fall back to English anyway. Having all cultures accepted would still help for cases like DateTime.ToString() and number formatting and such.

Is there an easy way to have all cultures automatically accepted (like in previous ASP.NET versions before Core)?

like image 856
Dunge Avatar asked Sep 06 '25 22:09

Dunge


1 Answers

This is the best I could do, using CultureInfo.GetCultures() to list them all.

If anyone have a justification on why I shouldn't do this (performance hit?), or a better alternative, feel free to post another answer!

app.UseRequestLocalization(options =>
{
    var cinfo = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
    var supportedCultures = cinfo.Select(t => t.Name).Distinct().ToArray();
    options.AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures)
        .SetDefaultCulture("en-US");
});
like image 66
Dunge Avatar answered Sep 10 '25 12:09

Dunge