Localization and MVC

by aanund 20. July 2010 08:16

An oft-written about subject, with several solutions. In our specific case we wanted a solution where the language part of the localization was gathered from the url, like ~/no/.

To do this we subclassed MvcRouteHandler like this:

public class LanguageRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string language = requestContext.RouteData.Values["language"] as string;

        if (!string.IsNullOrEmpty(language))
        {
            CultureInfo info = new CultureInfo(language);

            Thread.CurrentThread.CurrentUICulture = info;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(info.Name);
        }

        return base.GetHttpHandler(requestContext);
    }
}

When a route using this handler is triggered, it sets the CurrentCulture and CurrentUICulture for us, so that all calls to ResourceProviders will get correctly localized values.

To use this you must also modify how your routes are mapped.

Route defaultRoute = new Route(
     "{language}/{controller}/{action}/{id}",
     new RouteValueDictionary(
         new
         {
             language = "no",
             controller = "Home",
             action = "Index"
         }),
     new LanguageRouteHandler());
routes.Add("defaultRoute", defaultRoute);

You might also notice that we use ‘named’ routes as suggested by Chad Moran in http://www.chadmoran.com/blog/2009/4/21/optimizing-url-generation-in-aspnet-mvc-part-1.html.

Bookmark and Share

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About me

I work for EDB Consulting Group in Oslo, Norway.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010