Set default language culture for each client connection blazor-server

1.1k Views Asked by At

I have a blazor-server app and am looking for a way to be able to set a default language based on preference for each client that connects to the app.

I currently have this code in Startup.Configure() that successfully sets a default language for each user by calling user.GetPreferences().language, which gets their preferred language from the db . However, because this code only runs once when the server starts (right?), if the user changes their preference and then logs in from a different machine, the DefaultRequestCulture = new RequestCulture() still contains the old preference. So, it loads the app with their old language preference.

...
var options = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(user.GetPreferences().language),
    SupportedCultures = SupportedCultures,
    SupportedUICultures = SupportedCultures,
    RequestCultureProviders = new List<IRequestCultureProvider>
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    }
}
...

I also tried manually changing the CurrentCulture and CurrentUiCulture in the OnInitializedAsync() method of my MainLayout.razor. Doing this fixes the issue and connecting from a different machine sets the right default language for each client. But it seems like the culture gets set after the ui loads. This means that the user has to manually refresh the page for the language to change.

protected override async Task OnInitializedAsync()
{
    await LoadUser();
    ...
}
...
private async Task LoadUser()
{
    CultureInfo.CurrentCulture = new CultureInfo(user.GetPreferences().language);
    CultureInfo.CurrentUICulture = new CultureInfo(user.GetPreferences().language);
}

Is there an efficient way to set a default language each time a client connects by querying from the db?

Thanks

0

There are 0 best solutions below