A practical guide to building a multi-language Asp.Net 8 MVC application.
\ Abstract: A practical guide to building a multi-language Asp.Net 8 MVC application where all language resource strings are kept in a single shared file, as opposed to having separate resource files for each controller/view.
1 The need for a newer tutorialThere are a number of tutorials on how to build a multi-language application Asp.Net Core 8 MVC, but many are outdated for older versions of .NET or are vague on how to resolve the problem of having all language resources strings in a single file. So, the plan is to provide practical instructions on how that can be done, accompanied by code samples and a proof-of-concept example application.
1.1 Articles in this seriesArticles in this series are:
• ASP.NET 8 – Multilingual Application with single Resx file - Part 1
• ASP.NET 8 – Multilingual Application with single Resx file – Part 2 – Alternative Approach
• ASP.NET 8 – Multilingual Application with single Resx file – Part 3 – Form Validation Strings
• ASP.NET 8 – Multilingual Application with single Resx file – Part 4 – Resource Manager
2 Multilingual sites, Globalization and LocalizationI am not going to explain here what are benefits of having a site in multiple languages, and what are Localization and Globalization. You can read it in many places on the internet (see [4]). I am going to focus on how to practically build such a site in Asp.Net Core 8 MVC. If you are not sure what .resx files are, this may not be an article for you.
3 Shared Resources approachBy default, Asp.Net Core 8 MVC technology envisions separate resource file .resx for each controller and the view. But most people do not like it, since most multilanguage strings are the same in different places in the application, we would like it to be all in the same place. Literature [1] calls that approach the “Shared Resources” approach. In order to implement it, we will create a marker class SharedResoureces.cs to group all the resources.
\ Then in our application, we will invoke Dependency Injection (DI) for that particular class/type instead of a specific controller/view. That is a little trick mentioned in Microsoft documentation [1] that has been a source of confusion in StackOverflow articles [6]. We plan to demystify it here. While everything is explained in [1], what is needed are some practical examples, like the one we provide here.
4 Steps to Multilingual Application 4.1 Configuring Localization Services and MiddlewareLocalization services are configured in Program.cs:
\
private static void AddingMultiLanguageSupportServices(WebApplicationBuilder? builder) { if (builder == null) { throw new Exception("builder==null"); }; builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.AddMvc() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); builder.Services.ConfigureThis is just a dummy marker class to group shared resources. We need it for its name and type. It seems the namespace needs to be the same as the app root namespace, which needs to be the same as the assembly name. I had some problems when changing the namespace, it would not work. If it doesn't work for you, you can try to use the full class name in your DI instruction, like this one:
\
IStringLocalizer
\ There is no magic in the name "SharedResource", you can name it "MyResources" and change all references in the code to "MyResources" and all will still work.
\ The location seems can be any folder, although some articles ([6] claim it needs to be the root project folder I do not see such problems in this example. To me looks like it can be any folder, just keep your namespace tidy.
\
//SharedResource.cs=================================================== namespace SharedResources01 { /* * This is just a dummy marker class to group shared resources * We need it for its name and type * * It seems the namespace needs to be the same as app root namespace * which needs to be the same as the assembly name. * I had some problems when changing the namespace, it would not work. * If it doesn't work for you, you can try to use full class name * in your DI instruction, like this one: * IStringLocalizerIn the folder “Resources” create your language resources files, and make sure you name them SharedResources.xx.resx.
\
4.4 Selecting Language/CultureBased on [5], the Localization service has three default providers:
\
\ Since most apps will often provide a mechanism to set the culture with the ASP.NET Core culture cookie, we will focus only on that approach in our example. This is the code to set .AspNetCore.Culture cookie:
\
private void ChangeLanguage_SetCookie(HttpContext myContext, string? culture) { if(culture == null) { throw new Exception("culture == null"); }; //this code sets .AspNetCore.Culture cookie myContext.Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddMonths(1) } ); }\ Cookie can be easily seen with Chrome DevTools:
\
I built a small application to demo it, and here is the screen where I change the language:
\
Note that I added some debugging info into the footer, to show the value of the Request language cookie, to see if the app is working as desired.
4.5 Using Localization Services in the ControllerIn the controller is of course the Dependency Injection (DI) coming in and filling all the dependencies. The key thing is we are asking for a specific type=SharedResource. If it doesn't work for you, you can try to use the full class name in your DI instruction, like this one:
\
IStringLocalizer
\ Here is the code snippet:
```csharp public class HomeController : Controller { private readonly ILogger _logger; private readonly IStringLocalizer _stringLocalizer; private readonly IHtmlLocalizer _htmlLocalizer;
/* Here is of course the Dependency Injection (DI) coming in and filling * all the dependencies. The key thing is we are asking for a specific * type=SharedResource. * If it doesn't work for you, you can try to use full class name * in your DI instruction, like this one: * IStringLocalizerrazor-cshtml @* LocalizationExample.cshtml ====================================================*@ @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Localization
@model LocalizationExampleViewModel
@* Here is of course the Dependency Injection (DI) coming in and filling all the dependencies. The key thing is we are asking for a specific type=SharedResource. If it doesn't work for you, you can try to use full class name in your DI instruction, like this one: @inject IStringLocalizer StringLocalizer *@
@inject IStringLocalizer StringLocalizer @inject IHtmlLocalizer HtmlLocalizer
@{
IStringLocalizer Localized in Controller: @Model.IStringLocalizerInController
@{ string? text1 = StringLocalizer["Wellcome"]; } IStringLocalizer Localized in View: @text1
IHtmlLocalizer Localized in Controller: @Model.IHtmlLocalizerInController
@{ string? text2 = "Wellcome"; } IHtmlLocalizer Localized in View: @HtmlLocalizer[@text2]
}
### 4.7 Execution result Here is what the execution result looks like: \ ![](https://cdn.hackernoon.com/images/eUn59ClVtWU6R4iSzcVC45bTj4f1-2024-11-22T09:24:19.103Z-l9xo6akn2t4jj7k8j8jch0qd) Note that I added some debugging info into the footer, to show the value of the ***++Request language cookie++***, to see if the app is working as desired. ### 4.8 Problem with IHtmlLocalizercsharp //Program.cs=========================================================================== namespace SharedResources01 { public class Program { public static void Main(string[] args) { //=====Middleware and Services============================================= var builder = WebApplication.CreateBuilder(args);
//adding multi-language support AddingMultiLanguageSupportServices(builder); // Add services to the container. builder.Services.AddControllersWithViews(); //====App=================================================================== var app = builder.Build(); //adding multi-language support AddingMultiLanguageSupport(app); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=ChangeLanguage}/{id?}"); app.Run(); } private static void AddingMultiLanguageSupportServices(WebApplicationBuilder? builder) { if (builder == null) { throw new Exception("builder==null"); }; builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.AddMvc() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); builder.Services.Configure}
//SharedResource.cs=================================================== namespace SharedResources01 { /* * This is just a dummy marker class to group shared resources * We need it for its name and type * * It seems the namespace needs to be the same as app root namespace * which needs to be the same as the assembly name. * I had some problems when changing the namespace, it would not work. * If it doesn't work for you, you can try to use full class name * in your DI instruction, like this one: * IStringLocalizer StringLocalizer * * There is no magic in the name "SharedResource", you can * name it "MyResources" and change all references in the code * to "MyResources" and all will still work * * Location seems can be any folder, although some * articles claim it needs to be the root project folder * I do not see such problems in this example. * To me looks it can be any folder, just keep your * namespace tidy. */
public class SharedResource { }}
//HomeController.cs================================================================ namespace SharedResources01.Controllers { public class HomeController : Controller { private readonly ILogger _logger; private readonly IStringLocalizer _stringLocalizer; private readonly IHtmlLocalizer _htmlLocalizer;
/* Here is of course the Dependency Injection (DI) coming in and filling * all the dependencies. The key thing is we are asking for a specific * type=SharedResource. * If it doesn't work for you, you can try to use full class name * in your DI instruction, like this one: * IStringLocalizer}
//ChangeLanguageViewModel.cs===================================================== namespace SharedResources01.Models.Home { public class ChangeLanguageViewModel { //model public string? SelectedLanguage { get; set; } = "en";
public bool IsSubmit { get; set; } = false; //view model public List}
//LocalizationExampleViewModel.cs=============================================== namespace SharedResources01.Models.Home { public class LocalizationExampleViewModel { public string? IStringLocalizerInController { get; set; } public LocalizedHtmlString? IHtmlLocalizerInController { get; set; } } }
razor-cshtml @* ChangeLanguage.cshtml ===================================================*@ @model ChangeLanguageViewModel
@{
}
@* LocalizationExample.cshtml ====================================================*@ @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Localization
@model LocalizationExampleViewModel
@* Here is of course the Dependency Injection (DI) coming in and filling all the dependencies. The key thing is we are asking for a specific type=SharedResource. If it doesn't work for you, you can try to use full class name in your DI instruction, like this one: @inject IStringLocalizer StringLocalizer *@
@inject IStringLocalizer StringLocalizer @inject IHtmlLocalizer HtmlLocalizer
@{
IStringLocalizer Localized in Controller: @Model.IStringLocalizerInController
@{ string? text1 = StringLocalizer["Wellcome"]; } IStringLocalizer Localized in View: @text1
IHtmlLocalizer Localized in Controller: @Model.IHtmlLocalizerInController
@{ string? text2 = "Wellcome"; } IHtmlLocalizer Localized in View: @HtmlLocalizer[@text2]
} ```
6 References\ [1] https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization/make-content-localizable?view=aspnetcore-8.0
Make an ASP.NET Core app's content localizable
Provide localized resources for languages and cultures in an ASP.NET Core app
\ [3] https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization/select-language-culture?view=aspnetcore-8.0
Implement a strategy to select the language/culture for each request in a localized ASP.NET Core app
\ [4] https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-8.0
Globalization and localization in ASP.NET Core
\ [5] https://learn.microsoft.com/en-us/aspnet/core/fundamentals/troubleshoot-aspnet-core-localization?view=aspnetcore-8.0
Troubleshoot ASP.NET Core Localization
\ [6] https://stackoverflow.com/questions/42647384/asp-net-core-localization-with-help-of-sharedresources ASP.NET
Core Localization with help of SharedResources
\ [99] https://github.com/MarkPelf/AspNet8MultilingualApplicationWithSingleResxFile
All Rights Reserved. Copyright , Central Coast Communications, Inc.