Bilingual with .Net Core MVC or Globalization And Localization In ASP.NET Core MVC 3.1

Introduction 

 
Hello Folks,
 
Today we will add the Multilingual feature to our .NET Core MVC 3.1 project with a few simple steps.
 
A multilingual website allows the site to reach a wider audience. ASP.NET Core provides services and middleware for localizing into different languages and cultures.
 
Internationalization involves Globalization and Localization. Globalization is the process of designing apps that support different cultures. Globalization adds support for input, display, and output of a defined set of language scripts that relate to specific geographic areas.
 
Step 1  
 
So let's start by registering and configuring the localization in the startup class.
  1. public void ConfigureServices(IServiceCollection services)    
  2.       {    
  3.               
  4.           services.AddControllersWithViews();     
  5.           services.AddHttpContextAccessor();    
  6.   
  7.           #region snippet1    
  8.           services.AddLocalization(options => options.ResourcesPath = "Resources");     
  9.           services.AddMvc()    
  10.               .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)    
  11.               .AddDataAnnotationsLocalization();    
  12.          
  13.           services.Configure<RequestLocalizationOptions>(options =>    
  14.           {    
  15.               var supportedCultures = new[] { "en-US""hi-IN" };     
  16.               options.SetDefaultCulture(supportedCultures[0])    
  17.                   .AddSupportedCultures(supportedCultures)    
  18.                   .AddSupportedUICultures(supportedCultures) ;     
  19.           });   
  20.            #endregion  
  21.       }     
Add the below code in the Configure method in the startup class.
  1. var supportedCultures = new[] { "en-US""hi-IN" };    
  2.         var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])    
  3.             .AddSupportedCultures(supportedCultures)    
  4.             .AddSupportedUICultures(supportedCultures);    
  5.     
  6.         app.UseRequestLocalization(localizationOptions);    
 
 
Step 2
 
For file specific resources:
 
Add a Resources folder to your project and add files as per your project hierarchy. Also, you can create a language-specific resource file, like the file given below.
  • For Hindi -  Index.hi-IN.resx
  • For English -  Index.hi-IN.resx
  • For Common, If not available in above: Index.resx . 
This will also have an Index.designer.cs class, which is the main class to fetch the resource value.
 
You can create one by adding an access modifier in Index.resx only. There is no need to select this option in all remaining language-specific files for Index View.
 
 
For View exists in Views/Home/Index.cshtml.
 
Resources/Views/Home/Index.resx 
 or
 Resources/Views.Home.Index.resx
  
The same hierarchy will be followed for the controller and component model and so on.
 
 
For Shared resource
 
You need to create an empty class at the root of the project, as shown below: 
  1. // Dummy class to group shared resources  
  2.   
  3. namespace TestDemo  
  4. {  
  5.     public class CommonResources  
  6.     {  
  7.     }  
  8. }  
 
Also, the CommonResources resource file should be under the Resource folder.
 
 
We have now discussed the way to adding resource files. Now let's access the resources in our index.cshtml.
 
Index.cshtml
  1. @{  
  2.     ViewData["Title"] = "Home Page";  
  3. }  
  4. @using Microsoft.AspNetCore.Mvc.Localization   
  5. @inject IViewLocalizer Localizer  
  6. @inject IHtmlLocalizer<CommonResources> SharedLocalizer  
  7.   
  8.     @Localizer["Testing"].Value  
  9. <br/>   
  10. @SharedLocalizer["Test"]  
  11. <br/>  
  12. @TestDemo.Resources.Resource.ResourceManager.GetString("Testing", System.Globalization.CultureInfo.CurrentCulture)  
  13. <br />  
  14. <div class="text-center">  
  15.     <h1 class="display-4">Welcome</h1>  
  16.     <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>  
  17. </div>  
In the above image, we can see IViewLocalizer used for accessing view specific resource. Also, we can access the shared resource by IHtmlLocalizer<CommonResources> which we have created.
 
The alternate way to get the resource:
  1. @TestDemo.Resources.Resource.ResourceManager.GetString("Testing", System.Globalization.CultureInfo.CurrentCulture)   
Step 3
 
Let add a partial view for language selection and add its reference to _Layout.cshtml 
 
Now create _SelectLanguagePartial.cshtml under Views/Shared/_SelectLanguagePartial.cshtml 
  1. @using Microsoft.AspNetCore.Builder   
  2. @using Microsoft.AspNetCore.Localization  
  3. @using Microsoft.AspNetCore.Mvc.Localization  
  4. @using Microsoft.Extensions.Options  
  5.   
  6. @inject IViewLocalizer Localizer  
  7. @inject IOptions<RequestLocalizationOptions> LocOptions  
  8.   
  9. @{ var requestCulture = Context.Features.Get<IRequestCultureFeature>();  
  10.                 var cultureItems = LocOptions.Value.SupportedUICultures  
  11.                     .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })  
  12.                     .ToList();  
  13.                 var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}"; }  
  14.   
  15. <div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">  
  16.     <form id="selectLanguage" asp-controller="Home"  
  17.           asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"  
  18.           method="post" class="form-horizontal" role="form">  
  19.         <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> <select name="culture"  
  20.                                                                                                                onchange="this.form.submit();"  
  21.                                                                                                                asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">  
  22.         </select>  
  23.     </form>  
  24. </div>  
 Add the below code to your _Layout.cshtml
  1. @using Microsoft.AspNetCore.Mvc.Localization  
  2. @inject IViewLocalizer Localizer  
  3. <li class="nav-item">  
  4.    @Localizer["Testing"].Value  
  5. </li>  
  6. <li class="nav-item float-right">  
  7.    @await Html.PartialAsync("_SelectLanguagePartial")  
  8. </li>   
Step 4
 
Now please add SetLanguage method to your controller called by language change view
  1. [HttpPost]  
  2.      public IActionResult SetLanguage(string culture, string returnUrl)  
  3.      {  
  4.          Response.Cookies.Append(  
  5.              CookieRequestCultureProvider.DefaultCookieName,  
  6.              CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),  
  7.              new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }  
  8.          );  
  9.   
  10.          return LocalRedirect(returnUrl);  
  11.      }  
That's it, now build and run your project. The output will be like:
 
 
 

Summary

 
In this article, we have added a multilingual feature to our project with simple steps.
 
I hope it helps!