Blazor Localization - how do I set the locale for a session/circuit?

David Thielen 2,796 Reputation points
2023-10-10T04:22:39.0966667+00:00

Hi all;

I want to save off the locale the user selects as part of the user object. This way, as they continue using the website, including returning to the site, it is set to the locale they set.

I've got localization working as illustrated in this post (works perfectly). But it is built around the user selecting the locale each time. How can I set it for the session/circuit?

In other words, I load the user object and User.Locale has the value "en-US". How do I now have the localization give me the en strings?

And related question, how do I use that locale so that DateTimes and numbers are formatted according to the selected region?

thanks - dave

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,500 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ruikai Feng - MSFT 2,556 Reputation points Microsoft Vendor
    2023-10-10T08:05:33.6366667+00:00

    Hi,@David Thielen,You could add a custom culture provider follow this document

    var localizationOptions = new RequestLocalizationOptions()
        .SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures)
        .AddInitialRequestCultureProvider((new CustomRequestCultureProvider(async context =>
        {
            var cultureclaim = context.User.Claims.Where(x => x.Type == "Culture").FirstOrDefault();
            var result = new ProviderCultureResult(cultureclaim?.Value??"en-US");        
            return await Task.FromResult(result);
        })));
    
    app.UseRequestLocalization(localizationOptions);
    
    
    

    I scaffold Identity in the example, removed the selector,registed a user with Culture claim has value: es-CL

    User's image

    Now the result:

    10.10.2