Globalization in ASP.NET Core

How to globalize an application in an agile and simple way

This post is a follow up for Persisting data in .NET Core, focusing on the globalization of our application. Let’s have fun!

Introduction

While working on a project using ASP.NET Core we needed a simple way to globalize the application. In .NET, the most common way is to use .resxfiles, is through Visual Studio.

Visual Studio offers a very useful tool to manage, add, and edit or remove key-value tuples that allow one to use the functionality very easily.

This is possible only when working in Windows, so we were forced to investigate alternative options since manually managing the .resxfiles can be annoying. Through our research, we found the possibility of using JSON files. With a simple configuration, there is no need to depend on any external tools, only a text editor and a small library which we developed based on this post and this repository.

Configuring the project

The first step is adding the LocalizationCultureCore NuGet package to the project.

Next, we have to edit the Startup.cs and set the location of the JSON files in ConfigureServices.cs method:

In this example, the folder titled Resources contains the JSON files, so we will have to create it in the root of the project. The second line that we add allows us to use localization in views. Also, if you want to set a default culture, you can do it as it’s done in the last line of the example above.

Adding cultures

If we want to use multiple languages, we must add, for each one, a JSON file with the corresponding culture name. For example: en-US.json, fr-FR.json, es-MX.json, etc. Inside each file, we must put the keys that we will use later in the views and the controllers and their respective value, refer to the following example:

Using localization in controllers

In order to add the functionality in a controller, we will add the reference and update the constructor method:

And in the ViewData the value of that key is stored, according to the language that is configured.

Using localization in views

We also need to use this in the views. For that, we have to inject an IViewLocalizer on the view and we can then use it like in the controller:


Congratulations!

Our application is ready to use in as many languages as you want, so we can run and test it. Stay tuned for the next post explaining how to add SCSS to the style of our application.