Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to localize an ASP.NET MVC Application

I had to localize a ASP.NET Mvc Application and decided to share here how to do it in 3 easy steps:

First step: set up your routes

I opted to go with the following format{lang} as it provides the most benefits for SEO to the main domain name (instead of having one subdomain per language).  This is the route I set up:

name: "Localization",
url: "{lang}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Second step: set up your resources

Add a new folder Resources\Views to your project that mirrors the same hierarchy you have in your main View folder.

Then in each folder add Resx Files corresponding to your Views.  The naming of the resx files should match the following pattern: ViewName.{lang}.resx where lang is the Language Code.  Attention the language code is a 2 letters code and not a locale code (language-country)

Third step: localize your website

You need a [Localization] attribute to decorate your controller.  Below you can see the Class I built in order to implement it:

public class LocalizationAttribute : System.Web.Mvc.ActionFilterAttribute
    public override void OnActionExecuting(ActionExecutingContext filterContext)
        var defaultLang = "en";
        if (filterContext.RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
            defaultLang = filterContext.RouteData.Values["lang"].ToString();
            // check if lang is part of the supported Locals
            if (!Enum.IsDefined(typeof(Locals), defaultLang))
                // not part of the list, default to English and overwrite lang in url
                defaultLang = "en";
                filterContext.RouteData.Values["lang"] = "en";
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(defaultLang);

With that, your controller is able to manage localization (ex:load the right resx file depending on the lang in the URL) so it’s now time to display the localized strings in your views.  Just add the reference to the resource class at the beginning of your file (ex: using ProjectName.Resources.Views.Controller). Your texts will now be available as properties of the resx class.

That’s all, I hope you found it useful.

This post first appeared on Cezar Floroiu, please read the originial post: here

Share the post

How to localize an ASP.NET MVC Application


Subscribe to Cezar Floroiu

Get updates delivered right to your inbox!

Thank you for your subscription