When we need to develop multilanguage solution for Sharepoint the common approach is to keep all language specific resources in resx files (I don’t mention site variations here as they are out of scope of this post). In this case it is useful to have quick testing tool which will allow us to see how page or user control looks like using different locales. In this post I will describe how to implement custom http module which will allow to change current locale dynamically based on query string “lcid” parameter.
In my previous posts (here and here) about localization I described how Sharepoint sets locale of current thread based on locale of requested SPWeb. Summary of these posts: when user requests application _layout page – Sharepoint sets locale in SPRequestModule.PreRequestExecuteAppHandler; when user requests publishing page then Sharepoint initializes current thread locale in earlier steps in SPWeb.InitWeb() method.
The main idea – is to override locale initialized by Sharepoint by our locale using “lcid” query string parameter. From 2 mentioned places – the later one is SPRequestModule.PreRequestExecuteAppHandler. So we need to implement http handler and subscribe to PreRequestHandlerExecute event of http application. Also our custom http handler should be defined after SPRequestModule in <httpModules> section (it is required that SPRequestModule is the 1st module in Sharepoint) so its handler of PreRequestHandlerExecute will be executed after SPRequestModule.PreRequestExecuteAppHandler and will override locale set by Sharepoint.
The code of the http module is quite simple:
This module reads value specified in “lcid” query string parameter and if it represents valid locale id – changes locale of current thread using SPUtility.SetThreadCulture(…) method.
In order to make it work you need to add this custom http module in your web.config:
Now if you specify URL like http://example.com/_layouts/page.aspx – locale of http://example.com site will be used. But if you will append “lcid”query string parameter e.g. like this http://example.com/_layouts/page.aspx?lcid=1033 – then English locale (id = 1033) will be used to display content (of course you can use any valid locale id). It is not necessary to have single “lcid” query string param. You can use it with another parameters as well http://example.com/_layouts/page.aspx?param1=value1&lcid=1033.