从当前访问者那里获取CultureInfo并根据它设置资源?

时间:2012-02-23 13:36:05

标签: asp.net-mvc

我如何(在ASP .NET MVC中)获取当前访问者的CultureInfo(基于他/她的浏览器语言)?

我不知道从哪里开始。我试着查看浏览器发送的“Accept-Languages”标题。但这是最好的方式吗?

6 个答案:

答案 0 :(得分:53)

Request.UserLanguages是您正在寻找的财产。请记住,此数组可能包含由请求标头设置的任意(甚至非exsitent)语言。

<强>更新

示例:

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

答案 1 :(得分:7)

您可以使用与以下内容类似的代码来获取用户的各种详细信息(包括语言):

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

答案 2 :(得分:5)

我正在为一个明星标记这个问题并在此处分享一些代码,这些代码基本上将Request.UserLanguages转换为CultureInfo实例的数组,以便在您的应用程序中进一步使用。使用CultureInfo比使用ISO代码更灵活,因为使用CultureInfo可以访问文化的所有属性(如名称,两个字符的语言名称,本机名称......):

        // 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);
                 ctr++)
        {
            locale = Request.UserLanguages[ctr];
            if (!string.IsNullOrEmpty(locale))
            {

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

HTH

答案 3 :(得分:4)

看来Request.UserLanguages在更高的mvc版本中不可用(Asp.net核心mvc 2.0.2没有它。)

我为HTTPRequest做了扩展方法。如下使用它:

var requestedLanguages = Request.GetAcceptLanguageCultures();

该方法将按优先顺序(也称为“质量”)从Accept-Language标头中为您提供文化。

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))
            .Select(StringWithQualityHeaderValue.Parse)
            // 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()))
            .ToList();

        return preferredCultures;
    }
}

经过ASP.NET Core MVC 2.0.2

的测试

它类似于@mare的答案,但最新一些,不会忽略q(质量)。另外,您可能需要根据自己的使用情况将CultureInfo.InvariantCulture附加到列表的末尾。

答案 4 :(得分:1)

Asp.Net Core版本:使用 RequestLocalization ,即从HTTP请求中检索区域性。

在Startup.cs中-配置

app.UseRequestLocalization();

然后在Controller / Razor Page.cs中

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

答案 5 :(得分:-6)

var userLanguage = CultureInfo.CurrentUICulture;