DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. ASP.NET Core: Simple Localization and Language-Based URLs

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.

Gunnar Peipman user avatar by
Gunnar Peipman
·
Mar. 13, 17 · Tutorial
Like (1)
Save
Tweet
Share
40.50K Views

Join the DZone community and get the full member experience.

Join For Free

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.AddLocalization();
    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)
{
    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" });
    });
}

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)
    {
        if(!values.ContainsKey("lang"))
        {
            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
{
    get
    {
        if(!string.IsNullOrEmpty(_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]
    {
        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 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">
        <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 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.

ASP.NET ASP.NET Core

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Build a Spring Boot GraalVM Image
  • Real-Time Analytics for IoT
  • Introduction to Container Orchestration
  • Master Spring Boot 3 With GraalVM Native Image

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: