'Need an example on how to get preferred language from Accept-Language request header
I need a code example or library which would parse Accept-Language header and return me preferred language.
RFC2616 states that:
The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. Language tags are defined in section 3.10.
Accept-Language = "Accept-Language" ":" 1#( language-range [ ";" "q" "=" qvalue ] ) language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )Each language-range MAY be given an associated quality value which represents an estimate of the user's preference for the languages specified by that range. The quality value defaults to "q=1".
Further reading shows that there are too many "optional", "should", "may" and other turns of speech that prevent me from reinventing the wheel - all I want to know is what language user prefers, any browser answers this question billion times a day.
Any code snippet in any language (except Lisp and Assembler please) would be helpful.
Many thanks in advance!
Solution 1:[1]
Solution:
namespace ConsoleApplication
{
using System;
using System.Linq;
using System.Net.Http.Headers;
class Program
{
static void Main(string[] args)
{
string header = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
var languages = header.Split(',')
.Select(StringWithQualityHeaderValue.Parse)
.OrderByDescending(s => s.Quality.GetValueOrDefault(1));
}
}
}
Result:

Solution 2:[2]
Update for ASP.NET Core:
Microsoft has that built in by now.
Use the AcceptLanguageHeaderRequestCultureProvider:
IApplicationBuilder builder = ...;
builder.UseRequestLocalization(options => options
.AddInitialRequestCultureProvider(new AcceptLanguageHeaderRequestCultureProvider()));
you can then get the IRequestCultureFeature through the context:
// probably injected through your DI container
IHttpContextAccessor _accessor = ...;
await _accessor.HttpContext.Features
.Get<IRequestCultureFeature>().Provider
.DetermineProviderCultureResult(_accessor.HttpContext);
that returns a ProviderCultureResult?, you can then read the cultures (in form of IList<StringSegment>) from that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | weston |
| Solution 2 | Mafii |
