We live in a multilingual world, so offering your website in multiple languages is a great way to make it more user-friendly and connect with new audiences. To help you be successful, we’re going to share a detailed guide on how to create a multi language website. In this tutorial, we will cover:
You can download the example code used in this topic on GitHub.
Blazor Server identifies the display language based on the value of
CultureInfo.CurrentUICulture. The value set to those properties are strings. This string is a language tag which includes 2 information:
This is an example language tag: "en-US": the "en" indicates that the language is English, the "US" indicates that the language is used in "America". You can see the list of language tags in Microsoft Learn There is a rare case that you need to create your own language and the location, but that part does not include in this tutorial.
When creating a multi language website, you need to pay attention to:
There are 2 approaches when implement a multilingual website with Blazor Server, and it affects directly to the user experience.
A user can provide their preferred language in many ways:
There maybe a conflict between those ways. For example, a user may have entered your website with the language "en-US" in their URL, but their browser is set to French. Another example would be a user visits your website and select "en-US", then you store the language in their local storage; Later on, they revisit your website with the "fr" language in their URL. There is no standard strategy, every website resolves the conflict and select a language to display differently, and you need to do the same.
Each language tag is pair with a resource file. A resource file is an XML formatted file with the
<ComponentName>.<LanguageTag>.resx. For example, if your component is MyComponent.razor and you support French (fr) and English (en-US) then create 2 resource files with the name MyComponent.fr.resx and MyComponent.en-US.resx.
Program.cs. For example:
builder.Services.AddLocalization(options => options.ResourcesPath = "BlazorSchoolResources"); ... app.UseRequestLocalization();
IStringLocalizer<Your_Component>. For example, in the MyComponent:
@using Microsoft.Extensions.Localization @inject IStringLocalizer<MyComponent> Localizer @Localizer["String1"]
The String1 in the example is the key you defined in the resource file.