Changing the request culture for globalization and localization

In ASP.NET 2.0 we added several new features to make globalizing and localizing an application easier than ever before. One of the coolest features is the ability to declaratively localize entire controls as well as individual properties of controls. However, localization would be useless without the ability to choose which language and culture you want to display to the user. In many sites the user gets to choose their own language through some customization interface. So how does an ASP.NET developer set the culture?

There are three ways that I can think of that you can use to set the culture of a page:

  1. Set it in the web.config's <globalization> section. This is a great option if you want to force an entire site to have the exact same behavior when it comes to selecting a culture. Set the values of Culture and UICulture to "auto" to have ASP.NET auto-detect the browser's culture through the Accept-Language request header.
  2. Set it in the <%@Page %> directive. This works in the same way as the <globalization> section but is per page, including the auto-detect logic.
  3. For the most advanced customization of the selected culture you can override the page's InitializeCulture method and set the page's Culture and UICulture properties through code. The InitializeCulture method was added in ASP.NET 2.0 specifically for this scenario. We had to introduce a method that executes before the control tree is built such that when controls have their properties set they will use the appropriate resource set. You can place all this code in a single page base class and use the pageBaseType attribute of the <pages> section in web.config to have it be the base class for all pages in the application.

But how about setting the culture in the page's Init or Load phases? As it turns out, there are no phases of the page and control lifecycle that execute early enough so that every component on the page will realize the new culture settings. By the time Init happens, all the top-level controls on the page already have their properties set. Only dynamic controls, such as those inside templates, will realize the new culture settings since they typically get added as late as the Load or PreRender phases. InitializeCulture executes before the page and control lifecycle so that everyone can see its effects.

 

Random tidbit:

Ever get tired of spelling "localization," "globalization," and "internationalization"? Abbreviate them with L10N, G11N, and I18N! In "localization" there's an L, then 10 letters, and finally an N. Same idea for the other two. I just saved you a whole lot of typing :)

5 Comments

Comments have been disabled for this content.