Passive translation is one of the internationalization techniques. In passive translation, you have more control over the process of translating by directly interacting with the header of each request. The translation process automatically applies to text and formats (date time format, number format, etc...) to all pages. The only downside of this approach is the user is required to do a reload to see the translated page.
In this guide, you will be covered on how to i18n your website with 3 methodologies for detecting the user's preferred language:
Accept-Language
of the request header.You can download the example code used in this topic on GitHub.
To prepare your website for translations, you should have a basic understanding of the following subjects.
With this technique, you are going to introduce controller to Blazor Server. You must have a UI for the user to switch languages. Every time a user switches the language, you will redirect the request to the controller. Controller will change the language in the cookies and redirect the user to the current page causing a reload and the language will be updated also.
You first need to introduce the controller in Startup.cs
.
public void ConfigureServices(IServiceCollection services) { .... services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapControllers(); ... }); }
Follow the section "Localization" in the guide Internationalization and Localization, and once you have done so, you should have a Resources folder that contains all the language files. The next step is to use the Resources folder in Startup.cs
.
public void ConfigureServices(IServiceCollection services) { ... services.AddLocalization(options => options.ResourcesPath = "Resources"); services.Configure<RequestLocalizationOptions>(options => { options.AddSupportedCultures(new[] { "en", "fr" }); options.AddSupportedUICultures(new[] { "en", "fr" }); options.RequestCultureProviders = new List<IRequestCultureProvider>() { new CookieRequestCultureProvider() }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRequestLocalization(); ... }
The AddSupportedCultures
will enable automatically applied formats like date time, currencies, etc... to your website. The AddSupportedUICultures
will enable automatic applied translation of texts to your website. All 2 methods require a list of language codes that your website supports.
You can also set the default language for your website by calling options.SetDefaultCulture();
.
services.Configure<RequestLocalizationOptions>(options => { options.SetDefaultCulture("fr"); ... });
To switch the language, you need to change the value of the cookies and you will need to delegate the change cookies value process to a controller. Create a new folder with the name Controllers and add a CultureController.cs
.
[Route("[controller]/[action]")] public class CultureController : Controller { public IActionResult Set(string culture, string redirectUri) { if (culture is not null) { HttpContext.Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new(culture, culture))); } return LocalRedirect(redirectUri); } }
NavigationManager
to switch languageYou need to use NavigationManager
to navigate to the CultureController
to switch the language. The following code is a demonstration about how to change the language.
@using Microsoft.Extensions.Localization @using System.Globalization <select @onchange="OnChangeLanguage"> <option value="">Select</option> <option value="en">English</option> <option value="fr">France</option> </select> @code { private void OnChangeLanguage(ChangeEventArgs e) { var uri = new Uri(NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped); var culture = CultureInfo.GetCultureInfo(e.Value as string); var cultureEscaped = Uri.EscapeDataString(culture.Name); var uriEscaped = Uri.EscapeDataString(uri); NavigationManager.NavigateTo($"Culture/Set?culture={cultureEscaped}&redirectUri={uriEscaped}", forceLoad: true); } }
With this technique, you are showing the language in the address bar of the browser and the user can change it easily and can share the link with the language embedded in it. You are not required to provide a UI for the user to change the language.
Follow the section "Localization" in the guide Internationalization and Localization, and once you have done so, you should have a Resources folder that contains all the language files. The next step is to use the Resources folder in Startup.cs
.
public void ConfigureServices(IServiceCollection services) { ... services.AddLocalization(options => options.ResourcesPath = "Resources"); services.Configure<RequestLocalizationOptions>(options => { options.AddSupportedCultures(new[] { "en", "fr" }); options.AddSupportedUICultures(new[] { "en", "fr" }); options.RequestCultureProviders = new List<IRequestCultureProvider>() { new QueryStringRequestCultureProvider() }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRequestLocalization(); ... }
Once you have localized your website, the next step is to apply the translation. You need to apply the translation in the first Razor Component called by _Host.cshtml
. By default, it is App.razor
.
@inject NavigationManager NavigationManager ... @code { protected override void OnInitialized() { var uri = new Uri(NavigationManager.Uri); var urlParameters = HttpUtility.ParseQueryString(uri.Query); CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(urlParameters["culture"] ?? "en"); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(urlParameters["ui-culture"] ?? urlParameters["culture"] ?? "en"); } }
The example code extracts the culture
and ui-culture
key in the current url. If any, sets the respecitive culture as the current culture, if none, it will fall back to the en
culture.
The culture
and ui-culture
is the default key declared in QueryStringRequestCultureProvider
you have registered at Startup.cs
. You can also specify other keys in Startup.cs
and use it in App.razor
.
After you have applied the translation in Startup.cs
you can include the culture
and ui-culture
in URL to change the language. For example: http://localhost:5283/i18n?culture=fr, http://localhost:5283/i18n, http://localhost:5283/i18n?culture=en. Remember to force reload the page when users change the language.
With this technique, you are using the browser's settings to determine the language for the website. The language is automatically selected and you cannot control what language to show.
Follow the section "Localization" in the guide Internationalization and Localization, and once you have done so, you should have a Resources folder that contains all the language files. The next step is to use the Resources folder in Startup.cs
.
public void ConfigureServices(IServiceCollection services) { ... services.AddLocalization(options => options.ResourcesPath = "Resources"); services.Configure<RequestLocalizationOptions>(options => { options.AddSupportedCultures(new[] { "en", "fr" }); options.AddSupportedUICultures(new[] { "en", "fr" }); options.RequestCultureProviders = new List<IRequestCultureProvider>() { new AcceptLanguageHeaderRequestCultureProvider() }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRequestLocalization(); ... }
To change the language, change your browser website's preferred language.