Wednesday, May 18, 2011

An ASP.NET HttpModule to set the current culture to the user’s locale

My web application needs to display user information depend on its default culture.


I created an ASP.NET module:





using System;
using System.Globalization;
using System.Threading;
using System.Web;
namespace Gold.Translate
{
public class UserLocaleModule : IHttpModule
{
public void Init(HttpApplication httpApplication)
{
httpApplication.BeginRequest += (sender, eventArgs) =>
{
var app = sender as HttpApplication;
if (app == null)
{
throw new ApplicationException("Sender is null or not an HttpApplication");
}
var request = app.Context.Request;
if (request.UserLanguages == null request.UserLanguages.Length == 0) return;

var language = request.UserLanguages[0];
if (language == null) return;

try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
catch
{}
};
}

public void Dispose()
{

}
}
}

Configuration in web.config for classic mode:








<httpModules runAllManagedModulesForAllRequests="true">
<add name="UserLocale" type="Gold.Translate.UserLocaleModule, Gold.Translate" />
</httpModules>


Configuration in web.config for integration mode:








<modules runAllManagedModulesForAllRequests="true">
<add name="UserLocale" type="Gold.Translate.UserLocaleModule, Gold.Translate" />
</modules>



Migration Issues with IIS 7

When you migrated from IIS 6 to IIS 7 you must take care of needed changes. I fiund 2 good Urls tell you about all issues need to take care of it:

http://help.godaddy.com/article/4162

http://world.episerver.com/Documentation/Items/Tech-Notes/EPiServer-CMS-5/EPiServer-CMS-5-R2-SP1/Changes-Between-IIS6-and-IIS7/