Get CultureInfo from current visitor and setting resources based on that?

c# get browser language
what is http_accept_language
irequestculturefeature accept-language
how to set accept-language header in postman
set accept-language header javascript
missing accept-language header

How can I (in ASP .NET MVC) get the CultureInfo of the current visitor (based on his/her browser languages)?

I have no idea where to start. I tried looking into the "Accept-Languages" header sent by the browser. But is that the best way of doing it?

Asp.Net Core version: using RequestLocalization ie the culture is retrieved form the HTTP Request.

in Startup.cs - Configure


Then in your Controller/Razor Page.cs

var locale = Request.HttpContext.Features.Get<IRequestCultureFeature>();
var BrowserCulture = locale.RequestCulture.UICulture.ToString();

how to set site culture according to visitor location or region?, i'm using kentico mvc and i want to set culture of site dynamically on basis of visitor engine sites, by detect a site visitor's culture based on the visitor's browser settings. <summary> /// Get the current user's preferred locale. var preferredCulture = GetUserPreferredLocale(); var cultureInfo = CultureInfo. How can I (in ASP .NET MVC) get the CultureInfo of the current visitor (based on his/her browser languages)? I have no idea where to start. I tried looking into the "Accept-Languages" header sent

Request.UserLanguages is the property you're looking for. Just keep in mind that this array may contain arbitrary (even non-exsitent) languages as set by request headers.



// Get Browser languages.
var userLanguages = Request.UserLanguages;
CultureInfo ci;
if (userLanguages.Count() > 0)
        ci = new CultureInfo(userLanguages[0]);
         ci = CultureInfo.InvariantCulture;
    ci = CultureInfo.InvariantCulture;
// Here CultureInfo should already be set to either user's prefereable language
// or to InvariantCulture if user transmitted invalid culture ID

Changing the active culture, However, since changing the current culture is so essential, this chapter will and UICulture is automatically set based on the browser settings of your visitor. By calling the GetCultureInfo method, which returns a cached, read-only CultureInfo object. The current culture and UWP apps. In Universal Windows Platform (UWP) apps, the CurrentCulture property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture.

You can use code similar to the following to get various details from your user (including languages):

MembershipUser user = Membership.GetUser(model.UserName);
string browser = HttpContext.Request.Browser.Browser;
string version = HttpContext.Request.Browser.Version;
string type = HttpContext.Request.Browser.Type;
string platform = HttpContext.Request.Browser.Platform;
string userAgent = HttpContext.Request.UserAgent;
string[] userLang = HttpContext.Request.UserLanguages

Get current language in CultureInfo, E.g. if the language in Windows is set to French, I need to identify French and NET MVC) get the CultureInfo of the current visitor (based on his/her browser� If the UseUserOverride property is set to true and the culture identifier associated with the specified culture name matches the culture identifier of the current Windows culture, this constructor creates a CultureInfo that uses those overrides, including user settings for the properties of the DateTimeFormatInfo instance returned by the

It appears Request.UserLanguages is not available in later mvc versions ( core mvc 2.0.2 didn't have it.)

I made an extension method for HTTPRequest. Use it as follows:

var requestedLanguages = Request.GetAcceptLanguageCultures();

The method will give you the cultures from the Accept-Language header in order of preference (a.k.a. "quality").

public static class HttpRequestExtensions
    public static IList<CultureInfo> GetAcceptLanguageCultures(this HttpRequest request)
        var requestedLanguages = request.Headers["Accept-Language"];
        if (StringValues.IsNullOrEmpty(requestedLanguages) || requestedLanguages.Count == 0)
            return null;

        var preferredCultures = requestedLanguages.ToString().Split(',')
            // Parse the header values
            .Select(s => new StringSegment(s))
            // Ignore the "any language" rule
            .Where(sv => sv.Value != "*")
            // Remove duplicate rules with a lower value
            .GroupBy(sv => sv.Value).Select(svg => svg.OrderByDescending(sv => sv.Quality.GetValueOrDefault(1)).First())
            // Sort by preference level
            .OrderByDescending(sv => sv.Quality.GetValueOrDefault(1))
            .Select(sv => new CultureInfo(sv.Value.ToString()))

        return preferredCultures;

Tested with ASP.NET Core MVC 2.0.2

It's similar to @mare's answer, but a bit more up-to-date and the q (quality) is not ignored. Also, you may want to append the CultureInfo.InvariantCulture to the end of the list, depending on your usage.

CultureInfo.CurrentCulture Property (System.Globalization , Globalization.CultureInfo CurrentCulture { get; set; }. C# An object that represents the culture used by the current thread. Name); // Display the name of the current UI culture. Console If the thread is a thread pool thread that is executing a task-based asynchronous operation and the app targets the . Resources.Core. Using CultureInfo.CurrentCulture.IetfLanguageTag always uses Microsofts default values for the given culture and completely ignores changes made by the user. For example here in Germany default date format is '' but I manually configured this to be ISO 8601 compliant: 'yyyy-mm-dd' but this is ignored within WPF apps most of the time (some special controls like xceeds Grid behave

I am marking this question for myself with a star and sharing here some code that essentially turns the Request.UserLanguages into an array of CultureInfo instances for further use in your application. It is also more flexible to work with CultureInfo than just the ISO codes, because with CultureInfo you get access to all the properties of a culture (like Name, Two character language name, Native name, ...):

        // Create array of CultureInfo objects
        string locale = string.Empty;
        CultureInfo[] cultures = new CultureInfo[Request.UserLanguages.Length + 1];
        for (int ctr = Request.UserLanguages.GetLowerBound(0); ctr <= Request.UserLanguages.GetUpperBound(0);
            locale = Request.UserLanguages[ctr];
            if (!string.IsNullOrEmpty(locale))

                // Remove quality specifier, if present.
                if (locale.Contains(";"))
                    locale = locale.Substring(0, locale.IndexOf(';'));
                    cultures[ctr] = new CultureInfo(locale, false);
                catch (Exception) { continue; }
                cultures[ctr] = CultureInfo.CurrentCulture;
        cultures[Request.UserLanguages.Length] = CultureInfo.InvariantCulture;


ASP.NET Core 3.0 MVC Request Localization or How to Set the , NET Core 3.0 is a matter of setting the culture of the thread that is going to handle the request. localized content to the visitor, by mapping a Culture to that language. string resources but even how dates and numbers are formatted. For a culture to be used by the application as the current culture,� The CurrentCulture property represents the culture that the current thread uses. The CurrentUICulture property represents the current culture that Resource Manager uses to look up culture-specific resources at run time. There are three ways to set the Culture information in an ASP.NET application: application level, page level, and thread level.

Localisation in ASP.NET Core Razor Pages, 问题How can I (in ASP .NET MVC) get the CultureInfo of the current visitor (based on his/her browser languages)? I have no idea where to start. I tried looking� I'm not sure if this is a bug or just 'by design'. My user Region and Language are set to China and Chinese (for display), but CultureInfo.CurrentUICulture is en-US during

从当前访问者那里获取CultureInfo并根据它设置资源?, This article will look at the configuration required to prepare a site for is required to select the content based on the current request culture. Models { public class CultureSwitcherModel { public CultureInfo CurrentUICulture { get; set ; } Using Resource Files In Razor Pages Localisation fast_forward� Can i get the regional setting changed by user while running application. E.g. When application is started, Culture is en-US . After some time user changes it to some other culture. How can i track this change. I want my application date , time display to change based on current setting. I tried

User Mathias Lykkegaard Lorenzen, [英]Get CultureInfo from current visitor and setting resources based on that? 本文翻译自 Mathias Lykkegaard Lorenzen 查看原文 2012-02-23 34187�

  • This is a much better answer.
  • Quote: Typically these consist of a two-character codes for the language, a hyphen, and a two-character code for the culture, such as "en-us" for U.S. English and "fr-ca" for Canadian French.. So it's a string[] array containing values like those.
  • I've just been working with this, so just for anyone looking at this in the future, Request.UserLanguages is essentially a comma separated version of Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"]. The first item in the array will just be the country code (e.g. 'en-GB') and subsequent items will usually contain a 'weighting' (e.g. 'en-US;q=0.8'), for example mine is "en-GB,en-US;q=0.8,en;q=0.6" so you also might need to split each item again to find the actual code and the weighting.
  • The general form of these language tags is specified in RFC 5646 ( ). If you assume "ab-CD", you'll get thrown when somebody specifies an alphabet (sd-Arab-PK).
  • I'm actually running into this at work which is why I brought it up. For Taiwan, IE9- sends "zh-TW". IE10+ sends "zh-Hant-TW". I don't actually care about malicious users since they're just going to get fallback stuff, I do care about how there are now multiple ways to "spell" a particular locale.
  • Be careful, this answer does not handle: choosing the best culture from the user list, taking care of the priority value, setting the current culture for resource localization.
  • StringWithQualityHeaderValue - useful
  • @Phil, yeah, it's great. Parsing the header yourself would be a mess. There are a lot of little assumptions that could bite you.
  • new CultureInfo(sv.Value.ToString()) is likely to crash with a CultureNotFoundException if the client gives an invalid culture name!
  • @SandRock That is a good note to those using this. I'm not handling the exeptions for you. It's a good idea watch for a CultureNotFoundException and return a 400 or 500 or something to let them know you don't have that language support.
  • this gets current culture from server not client's browser