Over a million developers have joined DZone.

ASP.NET Core: Simple Localization and Language-Based URLs

DZone's Guide to

ASP.NET Core: Simple Localization and Language-Based URLs

In this post, we will take a look an easy, and compact, way to implement localization and globalization in your ASP.NET Core project.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

ASP.NET Core comes with new support for localization and globalization. I had to work with one specific prototyping scenario at work and as I was able to solve some problems that other people may face. So, I decided to share my knowledge and experience with my readers. This blog post is a short overview of simple localization that uses some interesting tweaks and framework level dependency injection.

My scenario was simple:

  1. We have a limited number of supported languages and the number of languages doesn’t change often.
  2. Deciding to use a new language means changes in the organization, and it will probably be a high-level decision.
  3. Although et-ee is the official notation for localization here, people are used to ee because it is our country domain.
  4. The application has a small amount of translations that are held in resource files (one per language).

As “ee” is not supported culture and “et” is not very familiar to regular users here, so I needed a way how to hide mapping from “ee” to “et”; that way I don’t have to inject this logic to views where translations are needed.

NB! To find out more about localization and globalization in ASP.NET Core please read the official documentation about it at https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization

Setting Up Localization

Localization is different compared to previous versions of ASP.NET. We need some modifications to our startup class. Let’s take the ConfigureServices() method first.

public void ConfigureServices(IServiceCollection services)
    services.AddMvc();       services.Configure<RequestLocalizationOptions>(
        opts =>
            var supportedCultures = new List<CultureInfo>
                new CultureInfo("et"),
                new CultureInfo("en"),
                new CultureInfo("ru"),
            };               opts.DefaultRequestCulture = new RequestCulture("et");
            opts.SupportedCultures = supportedCultures;
            opts.SupportedUICultures = supportedCultures;var provider = new RouteDataRequestCultureProvider();
            provider.RouteDataStringKey = "lang";
            provider.UIRouteDataStringKey = "lang";
            provider.Options = opts;               opts.RequestCultureProviders = new[] { provider };
    );       services.Configure<RouteOptions>(options =>
        options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
    });// ...

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

You don’t have a LanguageRouteConstraint class yet in your code. It’s coming later. Notice how supported cultures are configured and a route based culture provider is added to the request culture provider's collection. These are important steps to get our site to support these cultures.

Now let’s modify the Configure() method of our startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
           if (env.IsDevelopment())
    }       app.UseStaticFiles();

    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);       app.UseMvc(routes =>
            name: "LocalizedDefault",
            template: "{lang:lang}/{controller=Home}/{action=Index}/{id?}"
        );           routes.MapRoute(
            name: "default",
            template: "{*catchall}",
            defaults: new { controller = "Home", action = "RedirectToDefaultLanguage" });

Notice how the localized route is defined.  lang:lang means that there is request parameter lang that is validated by an element with index “lang” from the constraints map. The default route calls the RedirectToDefaultLanguage() method of the Home controller. We will take a look at this method later.

Now let’s add a language route constraint to our web application project.

public class LanguageRouteConstraint : IRouteConstraint
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
            return false;
        }var lang = values["lang"].ToString();

        return lang == "ee" || lang == "en" || lang == "ru";

This constraint checks if a language route value is given, and if it is then a check is made to see if it has a valid value. Note how I use “ee” here, instead of “et”: it’s the route value from the URL where I have to use “ee” instead of “et.”

Redirecting to the Language Route

By default, all requests to MVC that don’t have valid language in the URL are handled by the RedirectToDefaultLanguage() method of the Home controller.

public ActionResult RedirectToDefaultLanguage()
    var lang = CurrentLanguage;
    if(lang == "et")
        lang = "ee";
    }return RedirectToAction("Index", new { lang = lang });

private string CurrentLanguage
            return _currentLanguage;
        }           if(RouteData.Values.ContainsKey("lang"))
            _currentLanguage = RouteData.Values["lang"].ToString().ToLower();
            if(_currentLanguage == "ee")
                _currentLanguage = "et";
        }if (string.IsNullOrEmpty(_currentLanguage))
            var feature = HttpContext.Features.Get<IRequestCultureFeature>();
            _currentLanguage = feature.RequestCulture.Culture.TwoLetterISOLanguageName.ToLower();
        }           return _currentLanguage;

Here we have to replace “et” with “ee” to have a valid default URL. When one language routes the CurrentLanguage property, it gives us the current language from the route. If it is not language route then language by culture is returned.

Building a Custom String Localizer

As we have one resource file per language, and as views are using, in large part, the same translation strings, we don’t need to go with a resource file per view strategy. It would introduce many duplications and we can avoid it by using just one StringLocalizer<T>. There are reasons why we need a custom string localizer, like the “ee” and “et” issue: “ee” is an unknown culture in .NET and we have to translate it to “et” to ask for resources.

public class CustomLocalizer : StringLocalizer<Strings>
    private readonly IStringLocalizer _internalLocalizer;public CustomLocalizer(IStringLocalizerFactory factory, IHttpContextAccessor httpContextAccessor) : base(factory)
        CurrentLanguage = httpContextAccessor.HttpContext.GetRouteValue("lang") as string;
        if(string.IsNullOrEmpty(CurrentLanguage) || CurrentLanguage == "ee")
            CurrentLanguage = "et";
        }           _internalLocalizer = WithCulture(new CultureInfo(CurrentLanguage));
    }public override LocalizedString this[string name, params object[] arguments]
            return _internalLocalizer[name, arguments];
    }       public override LocalizedString this[string name]
            return _internalLocalizer[name];
    }public string CurrentLanguage { get; set; }

Our custom localizer is actually a wrapper that translates “ee” and empty language to “et”. This way we have one localizer class to injeect to views that need localization. Base class StringLocalizer<T> gets Strings as type and this is the name of resource files.

Example of a Localized View

Now let’s take a look at view that uses custom localizer. It’s a simple view that outputs a list of articles and below the articles, there is a link to all news lists. Link text is read from the resource string called “AllNews.”

@model CategoryModel
@inject CustomLocalizer localizer

<section class="newsSection">
    <header class="sectionHeader">
    @Html.DisplayFor(m => m.CategoryContent, "ContentList")
    <div class="sectionFooter">
        <a href="@Url.Action("Category", new { id = Model.CategoryId })" class="readMoreLink">@localizer["AllNews"]</a>

Wrapping Up

ASP.NET Core comes with new localization support and it is different from the one used in previous ASP.NET applications. It was easy to create language based URLs, and also to handle the special case where local people are used with “ee” as the language code instead of the official code “et.” We were able to achieve decent language support for applications where new languages are not added often. Also, we were able to keep things easy and compact. We wrote a custom string localizer class to handle mapping between “et” and “ee,” and we wrote just a few lines of code for it. And as it turned out, we also got away with a simple language route constraint. Our solution is a good example of how flexible ASP.NET Core is on supporting both small and big scenarios of localization.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

localization ,asp.net core ,web dev ,globalization

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}