Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET C# How to get user language from header?

Tags:

c#

asp.net

Is there any method to get the user language like the following java codes in C#?

request.getHeader("Accept-Language")
like image 549
user2018783 Avatar asked Dec 23 '13 02:12

user2018783


People also ask

What is ASP.NET C?

ASP.NET is an open source web framework, created by Microsoft, for building modern web apps and services with . NET. ASP.NET is cross platform and runs on Linux, Windows, macOS, and Docker.

Is ASP.NET just C#?

C# is a CLS programming language designed for the . NET framework. ASP.NET is part of the . NET framework allowing you to write web applications using any CLS compliant language such as C#, VB.NET, F#, ...

Can I use .NET with C?

. NET Framework is an object oriented programming framework meant to be used with languages that it provides bindings for. Since C is not an object oriented language it wouldn't make sense to use it with the framework.

Can I learn ASP.NET without C#?

Yes, you can learn them both at the same time, it is often easier to start if you know C# or VB beforehand, but not a requirement at all to be successful. There are many places to start, but 4GuysFromRolla.com is a great tutorial site.


2 Answers

You can use Request.UserLanguages. This propery contains a sorted string array of client language preferences MSDN.

You can get the default client language, like this:

var userLanguages = Request.UserLanguages;
var ci = userLanguages.Count() > 0 
    ? new CultureInfo(userLanguages[0])
    : CultureInfo.InvariantCulture;
like image 161
alexmac Avatar answered Oct 12 '22 23:10

alexmac


Extending on @alexmac's answer:

Request.UserLanguages returns an array of language-culture;priority pairs, see Mozilla WebDocs. Split the array items and discard the priority part, then filter for the "*" wildcard. The call to new CultureInfo(cultureName) will raise a CultureNotFoundException if cultureName is not found (was ArgumentEcception prior to .NEt 4), so I enclose it in a try/catch and default to InvariantCulture.

// get the user's language / culture settings from the 'accept-language' request header
var userLanguages = httpContext.Request.UserLanguages
    // split the 'language-culture;priority pair and use only the first part:
    .Select(userLanguageAndCultureWithPriority
        => userLanguageAndCultureWithPriority.Split(';')[0])
    // filter wildcard:
    .Where(userLanguageAndCulture => userLanguageAndCulture != "*")
    .ToArray();

CultureInfo ci;

try
{
    ci = userLanguages?.Count() > 0
        ? new CultureInfo(userLanguages[0])
        : CultureInfo.InvariantCulture;
}
catch (CultureNotFoundException)
{
    ci = CultureInfo.InvariantCulture;
}
like image 23
DhyMik Avatar answered Oct 12 '22 22:10

DhyMik