ASP.NET Core: Simple localization and language based URL-s

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 also other people may face I decided to share my knowledge and experience with my readers. This blog post is short overview of simple localization that uses some interesting tweaks and framework level dependency injection.

Source alert! Full sample solution built on ASP.NET Core 2.0 for this blog post is available at GitHub repository gpeipman/AspNetCoreLocalization.

My scenario was simple:

  1. We have limited number of supported languages and the number of languages doesn’t change often
  2. Coming of new language means changes in organization and it will probably be high level decision
  3. Although et-ee is official notation for localization here people are used with ee because it is our country domain
  4. Application has 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 I needed a way how to hide mapping from “ee” to “et” the way that 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 startup class. Let’s take ConfigureServices() method first.


public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization();
    services.AddMvc();


    services.Configure<
RouteOptions
>(options =>
    {
        options.ConstraintMap.Add(
"lang", typeof(LanguageRouteConstraint
));
    });

   
// ...


    services.AddSingleton<
IHttpContextAccessor, HttpContextAccessor>();
}

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

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


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection(
"Logging"
));
    loggerFactory.AddDebug();
         

   
if
(env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
   
else
    {
        app.UseExceptionHandler(
"/Home/Error"
);
    }

    app.UseStaticFiles();

   
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions
>>();
    app.UseRequestLocalization(options.Value);

    app.UseMvc(routes =>
    {


        routes.MapRoute(
            name:
"LocalizedDefault"
,
            template:
"{lang:lang}/{controller=Home}/{action=Index}/{id?}"

        );

        routes.MapRoute(
            name:
"default"
,
            template:
"{*catchall}"
,
            defaults:
new { controller = "Home", action = "RedirectToDefaultLanguage", lang = "et" });
    });
}

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

Now let’s add 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)
    {
       
if(!values.ContainsKey("lang"
))
        {
           
return false
;
        }

       
var lang = values["lang"
].ToString();

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

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

Request localization pipeline

There’s one issue. Routes are defined when MVC is configured. When localization is configured there are no routes. If we configure localization later then MVC has no idea about it. To solve this puzzle we will use special pipeline class with MiddlewareFilterAttribute.


public class LocalizationPipeline
{
   
public void Configure(IApplicationBuilder
app)
    {

       
var supportedCultures = new List<CultureInfo
>
                                {
                                   
new CultureInfo("et"
),
                                   
new CultureInfo("en"
),
                                   
new CultureInfo("ru"
),
                                };

       
var options = new RequestLocalizationOptions
()
        {

            DefaultRequestCulture =
new RequestCulture(culture: "et", uiCulture: "et"
),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        };

        options.RequestCultureProviders =
new[] { new RouteDataRequestCultureProvider() { Options = options } };

        app.UseRequestLocalization(options);
    }
}

To use pipeline class by middleware attribute we apply this attribute to controllers and view components where localization is needed.


[MiddlewareFilter(typeof(LocalizationPipeline))]
public class HomeController : Controller
{
   
// ...
}

Redirecting to language route

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


public ActionResult RedirectToDefaultLanguage()
{
   
var
lang = CurrentLanguage;
   
if(lang == "et"
)
    {
        lang =
"ee"
;
    }

   
return RedirectToAction("Index", new
{ lang = lang });
}

private string CurrentLanguage
{
   
get
    {
       
if(!string
.IsNullOrEmpty(_currentLanguage))
        {
           
return
_currentLanguage;
        }



       
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 on language route the CurrentLanguage property gives us current language from route. If it is not language route then language by culture is returned.

Building custom string localizer

As we have one resource file per language and as views are using in big part same translation strings we don’t go with resource file per view strategy. It would introduce many duplications and here we can avoid it by using just one StringLocalizer<T>. There reason why we need custom string localizer is the “ee” and “et” issue: “ee” is not known 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]
    {
       
get
        {
           
return
_internalLocalizer[name, arguments];
        }
    }

   
public override LocalizedString this[string
name]
    {
       
get
        {
           
return
_internalLocalizer[name];
        }
    }

   
public string CurrentLanguage { get; set; }
}

Our custom localizer is actually 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 localized view

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


@model CategoryModel
@inject CustomLocalizer
localizer

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

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 URL-s and also handle the special case where local people are used with “ee” as language code instead of official code “et”. We were able to achieve decent language support for application where new languages are not added often. Also we were able to keep things easy and compact. We wrote custom string localizer class to handle mapping between “et” and “ee” and we wrote just some lines of code for it. And as it turned out we also got away with simple language route constraint. Our solution is good example how flexible ASP.NET Core is on supporting both small and big scenarios of lozalization.

References



See also

22 thoughts on “ASP.NET Core: Simple localization and language based URL-s

Leave a Reply

Your email address will not be published. Required fields are marked *