Thursday, July 2, 2009

Retrieving Client Browser's Culture in ASP.NET

I fall in a couple of situations where I needed to get the client’s culture from the server side in an ASP.NET application. I googled this and found only client side solutions, but I knew there was some way to get this information because the ASP.NET framework supports client based culture (through the UI Culture = "Auto" in the page attributes and the globalization section in the web.config). The only way I thought of getting the client culture was from the Request object.

After examining the HTTP Headers collection I found the Accept-Language header. It contains information about the user's preferred languages.

This is a sample Accept-Language header:

Accept-Language
bg-BG,en-US;q=0.7,ar-BH;q=0.3

The languages are explicitly defined in the browser and their order is determined. You are probably wondering what this q-thing means. According to the RFC 3282 (Content Language Headers) it specifies the language quality or in other words the language priority set in the client's browser. In the example above bg-BG (Bulgarian (Bulgaria) has highest priority then en-US (English (United States)) and the last preferred language is ar-BH (Arabic (Bahrain)).

The Accept-Language header lists all languages set in the browser in a comma separated list which makes it easy to extract each language.

From ASP.NET you can access this header using the Headers collection in the Request object - Request.Headers["Accept-Language"]. Then you can process it the way you like.

Also instead of using Request.Headers["Accept-Language"] you can simply use the HttpRequest.UserLanguages to get a sorted string array of client language preferences.