Localization In Blazor Server With .NET Core 3.1

Introduction


Blazor is a framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET itself. There are two hosting models available for Blazor. Blazor Server and Blazor WebAssembly. Blazor server is officially shipped with .NET Core 3.0 and the current version is 3.1. Blazor WebAssembly is still in preview and will be released on May 2020, as per Microsoft roadmap. I have already written eight articles about Blazor Server on C# Corner. Please refer to below articles for more basics about Blazor framework.
 

Create a Blazor server application in Visual Studio 2019


Currently Visual Studio 2019 is available with Blazor server template. Since, we are creating an Employee app, I am using a Visual Studio extension to create Employee app with Entity framework Core. This extension will provide the template with four Razor components for CRUD actions and provide the Entity framework related codes. You can get the extension from this Visual Studio Marketplace link.
Install the extension and create Blazor project with this extension.
 
 
 
Give a name to the project and create it.
 
 
 
If you look at the project structure, you can see that Employee interface, Employee service, SqlDbContext and four Razor components are automatically created by the extension template.
 
You can execute “update-database” command in Package Manager Console to create SQL database and Employee table using EF Migration. By default, extension is using the local SQL server to store the data. If needed, you can change the server name and database name.
 
We are not modifying the default service layer. We can create a “Resource” folder inside the root directory and also create a “Pages” folder under that folder. You can give any name for Resource folder but should correctly mention inside the Startup class. I will explain those details soon. Inside the Resource folder, you should name the folder as “Pages”. This is the convention followed by Microsoft in .NET Core localization.
 
As I mentioned earlier, we have four Razor components for Employee CRUD actions. We can create four resource files for each component. Please note, you can create all the localization keys in single resource file also. But for simplicity and clarity, I am creating separate resource file for each component. We will create two supported language cultures in this application, “English” and “Malayalam”. Hence, we must create total eight resource files. As I pointed earlier, you can reduce single resource file for one culture if you wish.
 
We can add a new resource file under “Resources\Pages” folder for ListEmployees component.
 
 
 
You can notice that, I have not added any culture code with this file name. Because I will set English as my default request culture. Otherwise, we must provide the file name as “ListEmployees.en.resx”
 
You can add all keys and values for localization inside this file.
 
 
 
Above is the keys and values for ListEmployees component in English culture. We can add the Malayalam culture for same component.
 
 
 
All the keys in both culture for same component must be same. Values are different as per culture.
 
We can add resource files for remaining three components.
 
AddEmployee.resx

AddEmployee.ml.resx

EditEmployee.resx

EditEmployee.ml.resx

DeleteEmployee.resx

DeleteEmployee.ml.resx
 
We can modify the Razor components by replacing the static texts with resource keys.
 
Before that, we must modify “_Imports.razor” file by adding below using statement.
 
“Microsoft.Extensions.Localization”
 
 
 
We will use “IStringLocalizer” interface from above library to localize text file in every component.
We can modify ListEmployees component with below code.
 
ListEmployees.razor
  1. @page "/listemployees"  
  2. @inject IEmployeeService EmployeeService  
  3. @inject IStringLocalizer<ListEmployees> L  
  4.   
  5. <h2>@L["Title"]</h2>  
  6. <p>  
  7.     <a class="btn btn-primary" href='/addemployee'>@L["CreateEmployee"]</a>  
  8. </p>  
  9. @if (employees == null)  
  10. {  
  11.     <p>@L["Loading"]...</p>  
  12. }  
  13. else  
  14. {  
  15.     <table class='table'>  
  16.         <thead>  
  17.             <tr>  
  18.                 <th>@L["EmpName"]</th>  
  19.                 <th>@L["EmpDepartment"]</th>  
  20.                 <th>@L["EmpDesignation"]</th>  
  21.                 <th>@L["EmpCompany"]</th>  
  22.                 <th>@L["EmpCity"]</th>  
  23.             </tr>  
  24.         </thead>  
  25.         <tbody>  
  26.             @foreach (var employee in employees)  
  27.             {  
  28.                 <tr>  
  29.                     <td>@employee.Name</td>  
  30.                     <td>@employee.Department</td>  
  31.                     <td>@employee.Designation</td>  
  32.                     <td>@employee.Company</td>  
  33.                     <td>@employee.City</td>  
  34.                     <td>  
  35.                         <a class="btn btn-warning" href='/editemployee/@employee.Id'>@L["Edit"]</a>  
  36.                         <a class="btn btn-danger" href='/deleteemployee/@employee.Id'>@L["Delete"]</a>  
  37.                     </td>  
  38.                 </tr>  
  39.   
  40.             }  
  41.         </tbody>  
  42.     </table>  
  43. }  
  44.   
  45. @code {  
  46.     List<Employee> employees;  
  47.   
  48.     protected override async Task OnInitializedAsync()  
  49.     {  
  50.         employees = await EmployeeService.GetEmployees();  
  51.     }  
  52. }     
I have injected IStringLocalizer with current page name inside the component.
  1. @inject IStringLocalizer<ListEmployees> L  
We can use the variable “L” for localization and replace the static texts with resource keys.
We can modify the remaining three components in the same way.
 
AddEmployee.razor
  1. @page "/addemployee"  
  2. @inject NavigationManager NavigationManager  
  3. @inject IEmployeeService EmployeeService  
  4. @inject IStringLocalizer<AddEmployee> L  
  5.   
  6. <h2>@L["CreateEmployee"]</h2>  
  7. <hr />  
  8. <form>  
  9.     <div class="row">  
  10.         <div class="col-md-8">  
  11.             <div class="form-group">  
  12.                 <label for="Name" class="control-label">@L["EmpName"]</label>  
  13.                 <input for="Name" class="form-control" @bind="@employee.Name" />  
  14.             </div>  
  15.             <div class="form-group">  
  16.                 <label for="Department" class="control-label">@L["EmpDepartment"]</label>  
  17.                 <input for="Department" class="form-control" @bind="@employee.Department" />  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 <label for="Designation" class="control-label">@L["EmpDesignation"]</label>  
  21.                 <input for="Designation" class="form-control" @bind="@employee.Designation" />  
  22.             </div>  
  23.             <div class="form-group">  
  24.                 <label for="Company" class="control-label">@L["EmpCompany"]</label>  
  25.                 <input for="Company" class="form-control" @bind="@employee.Company" />  
  26.             </div>  
  27.             <div class="form-group">  
  28.                 <label for="City" class="control-label">@L["EmpCity"]</label>  
  29.                 <input for="City" class="form-control" @bind="@employee.City" />  
  30.             </div>  
  31.         </div>  
  32.     </div>  
  33.     <div class="row">  
  34.         <div class="col-md-4">  
  35.             <div class="form-group">  
  36.                 <input type="button" class="btn btn-primary" @onclick="@CreateEmployee" value="@L["Save"]" />  
  37.                 <input type="button" class="btn" @onclick="@Cancel" value="@L["Cancel"]" />  
  38.             </div>  
  39.         </div>  
  40.     </div>  
  41. </form>  
  42.   
  43. @code {  
  44.   
  45.     Employee employee = new Employee();  
  46.   
  47.     protected async Task CreateEmployee()  
  48.     {  
  49.         await EmployeeService.CreateEmployee(employee);  
  50.         NavigationManager.NavigateTo("listemployees");  
  51.     }  
  52.   
  53.     void Cancel()  
  54.     {  
  55.         NavigationManager.NavigateTo("listemployees");  
  56.     }  
  57. }     
EditEmployee.razor
  1. @page "/editemployee/{id}"  
  2. @inject NavigationManager NavigationManager  
  3. @inject IEmployeeService EmployeeService  
  4. @inject IStringLocalizer<EditEmployee> L  
  5.   
  6. <h2>@L["EditEmployee"]</h2>  
  7. <hr />  
  8. <form>  
  9.     <div class="row">  
  10.         <div class="col-md-8">  
  11.             <div class="form-group">  
  12.                 <label for="Name" class="control-label">@L["EmpName"]</label>  
  13.                 <input for="Name" class="form-control" @bind="@employee.Name" />  
  14.             </div>  
  15.             <div class="form-group">  
  16.                 <label for="Department" class="control-label">@L["EmpDepartment"]</label>  
  17.                 <input for="Department" class="form-control" @bind="@employee.Department" />  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 <label for="Designation" class="control-label">@L["EmpDesignation"]</label>  
  21.                 <input for="Designation" class="form-control" @bind="@employee.Designation" />  
  22.             </div>  
  23.             <div class="form-group">  
  24.                 <label for="Company" class="control-label">@L["EmpCompany"]</label>  
  25.                 <input for="Company" class="form-control" @bind="@employee.Company" />  
  26.             </div>  
  27.             <div class="form-group">  
  28.                 <label for="City" class="control-label">@L["EmpCity"]</label>  
  29.                 <input for="City" class="form-control" @bind="@employee.City" />  
  30.             </div>  
  31.         </div>  
  32.     </div>  
  33.     <div class="row">  
  34.         <div class="form-group">  
  35.             <input type="button" class="btn btn-primary" @onclick="@UpdateEmployee" value="@L["Update"]" />  
  36.             <input type="button" class="btn" @onclick="@Cancel" value="@L["Cancel"]" />  
  37.         </div>  
  38.     </div>  
  39. </form>  
  40.   
  41. @code {  
  42.   
  43.     [Parameter]  
  44.     public string id { getset; }  
  45.   
  46.     Employee employee = new Employee();  
  47.   
  48.     protected override async Task OnInitializedAsync()  
  49.     {  
  50.         employee = await EmployeeService.SingleEmployee(id);  
  51.     }  
  52.   
  53.     protected async Task UpdateEmployee()  
  54.     {  
  55.         await EmployeeService.EditEmployee(id, employee);  
  56.         NavigationManager.NavigateTo("listemployees");  
  57.     }  
  58.   
  59.     void Cancel()  
  60.     {  
  61.         NavigationManager.NavigateTo("listemployees");  
  62.     }  
  63. }     
DeleteEmployee.razor
  1. @page "/deleteemployee/{id}"  
  2. @inject NavigationManager NavigationManager  
  3. @inject IEmployeeService EmployeeService  
  4. @inject IStringLocalizer<DeleteEmployee> L  
  5.   
  6. <h2>@L["ConfirmDelete"]</h2>  
  7. <p>@L["CofirmMessage"] ? Id :<b> @id</b></p>  
  8. <br />  
  9. <div class="col-md-4">  
  10.     <table class="table">  
  11.         <tr>  
  12.             <td>@L["EmpName"]</td>  
  13.             <td>@employee.Name</td>  
  14.         </tr>  
  15.         <tr>  
  16.             <td>@L["EmpDepartment"]</td>  
  17.             <td>@employee.Department</td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td>@L["EmpDesignation"]</td>  
  21.             <td>@employee.Designation</td>  
  22.         </tr>  
  23.         <tr>  
  24.             <td>@L["EmpCompany"]</td>  
  25.             <td>@employee.Company</td>  
  26.         </tr>  
  27.         <tr>  
  28.             <td>@L["EmpCity"]</td>  
  29.             <td>@employee.City</td>  
  30.         </tr>  
  31.     </table>  
  32.     <div class="form-group">  
  33.         <input type="button" value="@L["Delete"]" @onclick="@Delete" class="btn btn-primary" />  
  34.         <input type="button" value="@L["Cancel"]" @onclick="@Cancel" class="btn" />  
  35.     </div>  
  36. </div>  
  37.   
  38. @code {  
  39.   
  40.     [Parameter]  
  41.     public string id { getset; }  
  42.     Employee employee = new Employee();  
  43.   
  44.     protected override async Task OnInitializedAsync()  
  45.     {  
  46.         employee = await EmployeeService.SingleEmployee(id);  
  47.     }  
  48.   
  49.     protected async Task Delete()  
  50.     {  
  51.         await EmployeeService.DeleteEmployee(id);  
  52.         NavigationManager.NavigateTo("listemployees");  
  53.     }  
  54.   
  55.     void Cancel()  
  56.     {  
  57.         NavigationManager.NavigateTo("listemployees");  
  58.     }  
  59. }     
Finally, we can modify the “ConfigureServices” and “Configure” methods in “Startup” class file.
 
Modify the ConfigureServices method
 
 
 
You can notice that, I have set the resource path as “Resources”. You can give any name for this resource path. But it should match with the actual folder name which contain the resource files.
 
ConfigureServices (method)
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddRazorPages();  
  4.             services.AddServerSideBlazor(options => options.DetailedErrors = true);  
  5.             services.AddSingleton<WeatherForecastService>();  
  6.   
  7.             services.AddDbContext<SqlDbContext>(options =>  
  8.                    options.UseSqlServer(Configuration.GetConnectionString("SqlDbContext")));  
  9.   
  10.             services.AddScoped<IEmployeeService, EmployeeService>();  
  11.   
  12.             services.AddLocalization(options => options.ResourcesPath = "Resources");  
  13.             var supportedCultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("ml") };  
  14.             services.Configure<RequestLocalizationOptions>(options =>  
  15.             {  
  16.                 options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");  
  17.                 options.SupportedUICultures = supportedCultures;  
  18.             });  
  19.         }  
We can modify the Configure method also by adding request localization pipeline.
 
Configure (method)
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2.         {  
  3.             if (env.IsDevelopment())  
  4.             {  
  5.                 app.UseDeveloperExceptionPage();  
  6.             }  
  7.             else  
  8.             {  
  9.                 app.UseExceptionHandler("/Error");  
  10.             }  
  11.   
  12.             app.UseRequestLocalization();  
  13.             app.UseStaticFiles();  
  14.   
  15.             app.UseRouting();  
  16.   
  17.             app.UseEndpoints(endpoints =>  
  18.             {  
  19.                 endpoints.MapBlazorHub();  
  20.                 endpoints.MapFallbackToPage("/_Host");  
  21.             });  
  22.         }  
We have completed the entire coding part. We can run the application.
 
 
Click “Employee data” link and click “New Employee” button to add a new employee data.
 
 
 
If you are using Chrome browser, go to Settings -> Advanced -> Languages and choose another language. I have added Malayalam culture in this application. Hence, I can set Malayalam as default language in language preferences. After that, we can refresh the page again.
 
 
 
You can notice that, the language is automatically changed to new culture. Application will automatically detect browser language preference and will show the text accordingly.
 
 

Conclusion


In this post, I have explained how to set localization in Blazor server app. I have created this project using a Visual Studio extension. I have added resource files for Razor components used for CRUD operations in Employee app. I have used two cultures English and Malayalam to demonstrate localization. I believe that, you have got a very good understanding on Localization with Blazor server app. Please feel free to send your valuable feedbacks.