Showing posts with label HttpModule. Show all posts
Showing posts with label HttpModule. Show all posts

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>