问题
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:
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.
回答2:
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
来源:https://stackoverflow.com/questions/63322167/how-do-i-get-the-blazor-client-browser-selected-language-so-i-can-use-the-righ