Localization in ASP.NET Core MVC with Example

Localization in ASP.NET Core  MVC with Example

Using Query Strings for Request Culture and Simplifying Localization with IStringLocalizer Interface

Let’s see how to implement Localization in ASP.NET Core MVC. In the first example, I am going to use the IStringLocalizer Interface in the controller to implement Localization. Additionally, when the user passes the desired language through the query string, it will display content in that language.

First, let’s configure the settings in the program.cs file.

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 

The AddLocalization method adds the localization service to the service container. I have added the supported cultures here. I have added two cultures: en for English and nl for Dutch. In the RequestCultureProviders, I have included QueryStringRequestCultureProvider(). This allows the system to determine the culture information from the query string. UseRequestLocalization initializes a RequestLocalizationOptions object.

program.cs
using Microsoft.AspNetCore.Localization; 
using Microsoft.Extensions.Options; 
using System.Globalization; 
 
.... 
.... 
.... 
 
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 
  
var supportedCultures = new[] 
    new CultureInfo("en"), 
    new CultureInfo("nl") 
}; 
  
builder.Services.Configure<RequestLocalizationOptions>(options => 
    options.DefaultRequestCulture = new RequestCulture("en"); 
    options.SupportedCultures = supportedCultures; 
    options.SupportedUICultures = supportedCultures; 
    options.RequestCultureProviders = new List<IRequestCultureProvider> 
        { 
            new QueryStringRequestCultureProvider() 
        }; 
}); 
  
var app = builder.Build(); 
..... 
..... 
..... 
 
app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value); 
  
app.UseHttpsRedirection(); 
..... 
..... 

Now, let’s create the resources. In the AddLocalization method, the ResourcesPath has been set as "Resources".

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 

So, first, I have created a "Resources" folder in the solution. There is a specific format for resource files. For example, if we are implementing localization in the HomeController, which is located inside the Controllers folder, the resource file name and folder structure should be as follows:

Resources/Controllers/HomeController.en.resx

or

Resources/Controllers/HomeController.en.resx

I chose the first option: Resources/Controllers/HomeController.en.resx. In the solution explorer below, you can see how the folder has been structured. Additionally, you can see there are two resource files: HomeController.en.resx and HomeController.nl.resx, one for English and another for Dutch.

Solution Explorer

The next file is a HomeController.en.resx. Here, I have added "Name" as "Hello" and "Value" as "Hello, World!".

Resources
The subsequent file is HomeController.nl.resx. Similar to the English file, here I have added the Dutch value for "Hello".
Resource
The following is the code for HomeController.cs. Here, IStringLocalizer has been injected into the controller. In the Index() method, _localizer["Hello"] has been assigned to ViewData["Greeting"].
public class HomeController : Controller 
    private readonly IStringLocalizer<HomeController> _localizer; 
  
        public HomeController(IStringLocalizer<HomeController> localizer) 
        { 
            _localizer = localizer; 
        } 
  
        public IActionResult Index() 
        { 
            ViewData["Greeting"] = _localizer["Hello"]; 
            return View(); 
        } 

Below is the code for Index.cshtml:

In this Index.cshtml file, the value of @ViewData["Greeting"] is displayed as the heading (<h1>). This will show the localized greeting message retrieved from the HomeController in the Index() action.

@{ 
    ViewData["Title"] = "Home Page"; 

  
<div class="text-center"> 
    <h1>@ViewData["Greeting"]</h1> 
</div> 

The below image is an output of above code. Here you can see when user passing the URL https://localhost:7051/Home/Index/Localization?culture=nl it gives Dutch message. Likewise, when user passing the https://localhost:7051/Home/Index/Localization?culture=en URL it gives English message. 

Output

View Localization with IViewLocalizer in ASP.NET Core MVC

In this guide, I will demonstrate how to implement View Localization using IViewLocalizer in ASP.NET Core MVC.

To enable view localization in ASP.NET Core MVC applications, add .AddViewLocalization() to builder.Services.AddControllersWithViews() in the program.cs file:

builder.Services.AddControllersWithViews().AddViewLocalization();

Next, create a resource folder structure as follows: Resources -> Views -> Home, and within the "Home" folder, create resource files for each supported language, such as Index.en.resx for English and Index.nl.resx for Dutch.

Below is the folder structure in the solution explorer:

In the Index.en.resx file, set the value for "Greeting" to "Hello, World!" in English. Similarly, in the Index.nl.resx file, set the value for "Greeting" to "Hallo Wereld!" in Dutch.

In your index.cshtml file, ensure you've added the Microsoft.AspNetCore.Mvc.Localization namespace. Then, inject IViewLocalizer and use it to display the localized greeting:

@using Microsoft.AspNetCore.Mvc.Localization 
@inject IViewLocalizer ViewLocalizer 
 
@{ 
    ViewData["Title"] = "Home Page"; 
 
<div class="text-center"> 
    <p>@ViewLocalizer["Greeting"]</p> 
</div>

The output of the above code will vary based on the culture specified in the URL. For example, when the URL includes culture=en, it will display the English content: https://localhost:7054/home/index/localization?culture=en

Similarly, when the URL includes culture=nl, it will display the Dutch content: https://localhost:7054/home/index/localization?culture=nl

Implementing view localization in this manner allows your ASP.NET Core MVC application to dynamically display content in different languages based on the specified culture.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC