Search code examples
blazorblazor-webassembly

blazor wasm read asp.net culture cookie at startup


I'm setting the culture cookie like this:

await JS.InvokeVoidAsync(
            "site.setCookie", 
            CookieRequestCultureProvider.DefaultCookieName, 
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(new CultureInfo(name))));

which will set the .AspNetCore.Culture cookie

and in Blazor Server in Startup/Program.cs I would call:

app.UseRequestLocalization

which will make it automatically read the ASP.net Culture Cookie and set the CurrentCulture;

UseRequestLocalization doesn't seem to be available in Blazor WASM,

how are we supposed to do this here, is there something built-in ?


Solution

  • found solution here: https://learn.microsoft.com/en-us/aspnet/core/blazor/globalization-localization?view=aspnetcore-7.0&pivots=webassembly#localization

    The culture needs to be set manually in in Program.cs before calling app.RunAsync():

    var app = builder.Build();
    
    var js = app.Services.GetRequiredService<IJSRuntime>();
    var result = await js.InvokeAsync<string>("blazorCulture.get");
    
    if (result != null)
    {
        var culture = new CultureInfo(result);
        CultureInfo.DefaultThreadCurrentCulture = culture;
        CultureInfo.DefaultThreadCurrentUICulture = culture;
    }
    
    await app.RunAsync();
    

    and we're getting it using js, not automatically from something like Response.Cookies