获取.AspNetCore2.0中的浏览器语言? [英] Get browser language in .AspNetCore2.0?

查看:374
本文介绍了获取.AspNetCore2.0中的浏览器语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从浏览器中获取默认语言,并使用以下代码来获取它:

I am trying to get the default language from the browser and I use the following code to get it:

var languages = HttpContext.Request.UserLanguages;

由于我使用以下工具测试的.NET Core 2不支持上述功能:

Since the above is not supported with .NET Core 2 I tested with:

var requestContext = Request.HttpContext.Features.Get<IRequestCultureFeature>();

但是,它返回null.获得语言的正确方法或替代方法是什么?

However, it returns null. What is the correct way or alternative to get the language?

推荐答案

IRequestCultureFeature提供了第一个匹配的语言,您的应用程序支持该语言.在Startup类的Configure()中定义了支持的语言的声明(请参见示例).如果仍然需要所有接受的语言作为简单的string[](如较早的Request.UserLanguages属性),请使用在Microsoft.AspNetCore.Http命名空间中定义的HeaderDictionaryTypeExtensions.GetTypedHeaders()扩展名:

IRequestCultureFeature provides the first matched language, which is supported by your application. Declaration of supported languages is defined in Configure() of your Startup class (see example). If you still need all accepted languages as a simple string[] like the older Request.UserLanguages property, then use the HeaderDictionaryTypeExtensions.GetTypedHeaders() extension defined in the Microsoft.AspNetCore.Http namespace:

// In your action method.
var languages = Request.GetTypedHeaders()
                       .AcceptLanguage
                       ?.OrderByDescending(x => x.Quality ?? 1) // Quality defines priority from 0 to 1, where 1 is the highest.
                       .Select(x => x.Value.ToString())
                       .ToArray() ?? Array.Empty<string>();

数组languages包含根据优先级参数q接受的语言的列表.具有最高优先级的语言是第一位的.要获取默认语言,请使用数组languages的第一个元素.

The array languages contains the list of accepted languages according to the priority parameter q. The language with the highest priority comes first. To get the default language take the first element of the array languages.

作为扩展方法:

using System.Collections.Generic;
using System.Linq;

using Microsoft.AspNetCore.Http;

public static class HttpRequestExtensions
{
    public static string[] GetUserLanguages(this HttpRequest request)
    {
        return request.GetTypedHeaders()
            .AcceptLanguage
            ?.OrderByDescending(x => x.Quality ?? 1)
            .Select(x => x.Value.ToString())
            .ToArray() ?? Array.Empty<string>();
    }
}

这篇关于获取.AspNetCore2.0中的浏览器语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆