3

I try to show and use the right digit separator depending on the clients browser selected language. I'm using a Blazor Server App. I've tried to use the 'Sytem.Globalization' namespace but this only shows the settings of the Server Side browser. Is there a way to get the Client browser language/culure settings?

  • 1
    Please use Google search before you post. The documentation on [localization for blazor](https://learn.microsoft.com/en-us/aspnet/core/blazor/globalization-localization?view=aspnetcore-3.1) is available in the Microsoft Docs. – Dennis VW Aug 09 '20 at 03:23
  • 2
    I did (of course). And if I Google again after 2 days I end up here looking at my own question. And btw the documentation in that page is not correct. They don't show how to get the cultureinfo (numberformat, dateformat) from the **clients browser selected language**. – Wim Kuijpers Aug 11 '20 at 05:57

2 Answers2

2

You could use javascripts navigator.language property via Interop.

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages

public static class JsInterop  
{  

    public static async Task<string[]> Languages()  
    {  
        return await JSRuntime.Current.InvokeAsync<string[]>("navigatorLanguages");  
    }  
}  

Add this to your javascript file

navigatorLanguages = function () {  
    return Promise.resolve(navigator.languages);  
}; 

This will return an array of string of the users preferred language.

Note: If you need to support IE10 or earlier you will need to use the navigator.browserLanguage instead.

John Rah
  • 1,757
  • 1
  • 14
  • 13
-1

I finally found it. One thing is sure: don't use anything like CurrentCulture and or System.Globalization to get the client browser language settings. You have to get this value BEFORE any Razor Component is loaded so I used the _Host.cshtml file to get the (Mvc.RazorPages.PageBase.) HttpContext. From there I used the "Accept-Language" from the HttpContext.Request.Headers StringValues which in my case returned: "nl,en-GB;q=0.9,en;q=0.8". And that turned out to be correct, nl (Dutch) is the first browser language and English the second. And now you can use CultureInfo: var culture = new System.Globalization.CultureInfo("en-GB"). To get the Decimal separator: char numberDecimalSeparator = Convert.ToChar(culture.NumberFormat.NumberDecimalSeparator). And if you have this you also can get the date format. Etc, etc

  • 1
    Sorry to say, but this is NOT correct. If you could not get the culture from CultureInfo, you were either running an older version of WASM, or you have configured the middleware on the server side wrong. Since Blazor-WASM 3.2.1 has been released, it added support for internationalization. Simply, anywhere in your code you can use `@CultureInfo.CurrentUICulture` or `@CultureInfo.CurrentCulture` to get the clients culture.. This works perfectly – Dennis VW Aug 16 '20 at 05:01