asp.net-mvc 从当前访问者那里获取 CultureInfo 并在此基础上设置资源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9414123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:46:03  来源:igfitidea点击:

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

asp.net-mvc

提问by Mathias Lykkegaard Lorenzen

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

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

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?

我不知道从哪里开始。我尝试查看浏览器发送的“接受语言”标头。但这是最好的方法吗?

采纳答案by Tino Mclaren

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

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

in Startup.cs - Configure

在 Startup.cs - 配置

app.UseRequestLocalization();

Then in your Controller/Razor Page.cs

然后在你的 Controller/Razor Page.cs

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

回答by Sergey Kudriavtsev

Request.UserLanguagesis 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.

Request.UserLanguages是您要查找的属性。请记住,此数组可能包含由请求标头设置的任意(甚至不存在)语言。

UPDATE

更新

Example:

例子:

// 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

回答by Chris

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

回答by Cory-G

It appears Request.UserLanguagesis not available in later mvc versions (Asp.net core mvc 2.0.2 didn't have it.)

它似乎Request.UserLanguages在更高的 mvc 版本中不可用(Asp.net core mvc 2.0.2 没有它。)

I made an extension methodfor HTTPRequest. Use it as follows:

我做了一个扩展方法进行HTTPRequest。使用方法如下:

var requestedLanguages = Request.GetAcceptLanguageCultures();

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

该方法将按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;
    }
}

Tested with ASP.NET Core MVC 2.0.2

测试过 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.InvariantCultureto the end of the list, depending on your usage.

它类似于@mare 的答案,但更新了一点,并且不会忽略 q(质量)。此外,您可能希望将 附加CultureInfo.InvariantCulture到列表的末尾,具体取决于您的使用情况。

回答by mare

I am marking this question for myself with a star and sharing here some code that essentially turns the Request.UserLanguagesinto 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, ...):

我用一颗星为自己标记了这个问题,并在此处分享了一些代码,这些代码实际上将Request.UserLanguages转换为 CultureInfo 实例数组,以便在您的应用程序中进一步使用。与仅使用 ISO 代码相比,使用 CultureInfo 也更灵活,因为使用 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

HTH

回答by jeffmaher

var userLanguage = CultureInfo.CurrentUICulture;

var userLanguage = CultureInfo.CurrentUICulture;