Get browser language in .AspNetCore2.0?

烈酒焚心 提交于 2020-06-25 07:56:11

问题


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;

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

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

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


回答1:


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>();

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.

As an extension method:

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>();
    }
}



回答2:


You need to add the localisation middleware to be able to get the IRequestCultureFeature feature:

public void Configure(IApplicationBuilder app)
{
    //...

    //Add this:
    app.UseRequestLocalization();

    //...
}

Now in your controller you can request the feature like this:

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



回答3:


You can get the browser language from the Request Headers

Write on your controller:

//For example --> browserLang = 'en-US'
var browserLang= Request.Headers["Accept-Language"].ToString().Split(";").FirstOrDefault()?.Split(",").FirstOrDefault();



回答4:


You have to add the localization middleware to enable parsing of the culture header, and then get the value through IRequestCultureFeature.

Check this link : https://github.com/aspnet/Mvc/issues/3549



来源:https://stackoverflow.com/questions/49381843/get-browser-language-in-aspnetcore2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!