Is there any method to get the user language like the following java codes in C#?
request.getHeader("Accept-Language")
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.
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#, ...
. 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.
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.
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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With