ASP.NET Core and Blazor

ASP.NET Core and Blazor Localization

Localize ASP.NET Core and Blazor applications the standard way, with the localizer interfaces, without writing a single original .resx file yourself: Soluling reads the strings from your source code, creates the original resource files, and builds the localized .resx files and satellite assemblies.

Razor Pages, MVC, Web API, Blazor Server, and Blazor WebAssembly share the same process. This guide follows the Razor Pages Driving sample, a small driving time calculator, and shows what differs in Blazor where it matters: the localizers, the setup, and how the language is chosen.

Download Soluling

You build C# Driving.csproj Soluling 150 60 Driving Time Driving distance: Speed: Round time Calculate Fahrzeit Fahrstrecke: Geschwindigkeit: Ungefähre Uhrzeit Berechnen The page as it is in the project has been translated in the editor Localized resources C# Driving.csproj fi Index.fi.resx fi IndexModel.fi.resx de Index.de.resx de IndexModel.de.resx Localized .resx files for each language, next to the project You build C# Driving.csproj Soluling 150 60 Driving Time Driving distance: Speed: Round time Calculate Fahrzeit Fahrstrecke: Geschwindigkeit: Ungefähre Uhrzeit Berechnen The page as it is in the project has been translated in the editor Localized resources C# Driving.csproj fi Index.fi.resx fi IndexModel.fi.resx de Index.de.resx de IndexModel.de.resx Localized .resx files for each language, next to the project
Soluling keeps Driving.csproj and writes the localized .resx files into the project. Deploy the satellite assemblies with the application.
Input
Visual Studio project or solution (.csproj, .sln) with localizer strings in .cshtml, .razor, and .cs files
Output
Localized .resx files (Resources\Pages\Index.fi.resx) and satellite assemblies
Runtime
The request localization middleware; Blazor WebAssembly uses the language stored in the browser
Original .resx
Created by Soluling from the source code; you don't maintain it

On this page

Tutorial

Localize an ASP.NET Core or Blazor application, step by step

Six steps take the application from hard-coded English to localized resource files and satellite assemblies.

01

Prepare: use a localizer for every text

These rules are the same everywhere:

  1. The text is the key. Write localizer["Enter values and click Calculate."] instead of the text. You don't create a .resx file. Each type you pass to IStringLocalizer<T> gets its own resource file; pass the same type everywhere to have only one.
  2. Use placeholders, not interpolation. Write localizer["Sport {0}", Value.Id]. An interpolated string, localizer[$"..."], is a different key every time, and Soluling can't find it.
  3. Comment the strings. A //loc comment on the same line in C# code is shown to the translator, for example, //loc 0: Hours or minutes.
  4. Use plural patterns for numbers. The Driving sample passes its plural pattern through the localizer and formats it with MultiPattern.FormatMulti from Soluling's .NET library. See patterns.

Soluling reads the text after //loc up to the end of the line and gives it to the translator as the comment of the string. Use comments to tell how the string is used, especially if its meaning is ambiguous. For example, Round time can mean a time that is rounded or the time of a lap, and only a comment tells the translator which one. Comments work in .cs files and in any C# code, such as the @code block of a .razor file or the @{ } block of a .cshtml file.

@{
  var title = localizer["Sports"];  //loc Title of the page that lists the sports
}
<h1>@title</h1>

Do not add the comment after a string in markup, such as <h1>@localizer["Sports"] //loc Title</h1>. The browser would show the comment in the page, and Soluling would take the rest of the line, including </h1>, as the comment. Move the string into a code block as above.

Razor Pages and MVC

  • Add the view localizer to every view and page in _ViewImports.cshtml: @using Microsoft.AspNetCore.Mvc.Localization and @inject IViewLocalizer Localizer. Then write @Localizer["Driving Time"].
  • In controllers, page models, and view models, inject IStringLocalizer<T> with the constructor. Web API has no views, so it uses only this.
  • For data annotations, add [Display(Name = "Name")] to properties and enum values, and ErrorMessage to the validation attributes. If the models are in a class library, use a shared resource. See Data annotations in class libraries.

Blazor

  • Make the assembly name and the default namespace the same, or Blazor can't find the translations. Add @using Microsoft.Extensions.Localization to _Imports.razor. Blazor WebAssembly also needs the Microsoft.Extensions.Localization NuGet package.
  • Blazor supports only IStringLocalizer: add @inject IStringLocalizer<Index> localizer to each component. In a component's code-behind, you can use [Inject]; in a plain class, the constructor.
  • For a text with HTML, cast the value to MarkupString, but only for your own resources, never for user input.
Wrapping the texts of a Razor page with the localizers Before, the page has hard-coded English texts and the page model builds the result with an interpolated string. After, the page uses IViewLocalizer, and the page model uses IStringLocalizer with a plural pattern. Soluling creates the original resource files from the code, and the Finnish files have the translations. Before <h1>Driving Time</h1> Message = $"Driving time is {hours} hours {minutes} minutes"; ✕ Stays English, no plural forms Internationalize After: Pages\Index.cshtml and Index.cshtml.cs in the Driving sample <h1>@Localizer["Driving Time"]</h1> Message = MultiPattern.FormatMulti(localizer["Driving time is{plural, ...}"], hours, minutes); //loc 0: Hours or minutes Index.fi.resx and IndexModel.fi.resx Driving Time Finnish Ajoaika Driving time is... Original Driving time is{plural, zero { } one { {0} hour } other { {0} hours }}{plural, one {{0} minute} other {{0} minutes}} Finnish Ajoaika on{plural, zero { } one { {0} tunti } other { {0} tuntia }}{plural, one {{0} minuutti} other {{0} minuuttia}} ✓ No original .resx to maintain; the plural forms of each language
In Blazor, the page line is the same with @localizer from IStringLocalizer.
02

Add: create a Soluling project

Drag and drop the .csproj (or the .sln) on Soluling. Project Wizard starts.

  • On the Localizer options page, keep the defaults: Soluling scans the source code for the localizer calls and creates the original .resx files, by default only in memory. You can also let it write them, or use files you extract yourself.
  • On the Resources page, keep the default, the .resx files.
  • If the application has been localized before, Soluling finds the existing localized files and imports their translations.
  • On the Select Languages page, add the target languages, and click Finish.

New pages, views, controllers, and components need no extra settings: Soluling finds them the next time it scans the project.

Project Wizard Driving.csproj goes through Project Wizard's Localizer options page (scan the source code, original .resx files in memory), Resources page, Existing translations page, and Select Languages page (Finnish and German). Drop Driving.csproj or the .sln Localizer options Scan source code Original .resx in memory Resources ☑ ResX Existing translations Index.fi.resx IndexModel.fi.resx ✓ Imported Languages Finnish (fi) German (de) The Existing translations page appears only when Soluling finds localized files.
03

Translate: the strings of each page and class

The project tree has a resource file for each view, page, and type you pass to a localizer, such as Pages\Index.resx and Pages\IndexModel.resx, with the strings in the grid and your //loc comments next to them. Placeholders such as {0} are protected, and plural patterns open in the plural editor.

  • Machine translation and translation memory. Click Use Machine Translation to translate with Amazon, Claude, DeepL, Google, Microsoft, ModernMT, or MyMemory, and reuse earlier translations from translation memory and terminology.
  • External translators. Send a translation package, an Excel file, or XLIFF to a translator, and import the results back. See teamwork.
  • Translators in a browser. Upload the project to Soluling Cloud and let translators work in Translate.
04

Check: find problems before release

Pseudo translation. Click Translate | Pseudo Translations | Fill, build, and run the application. Pseudo translations are longer and use accented characters, so texts that don't fit and strings still in the code (shown in plain English) stand out. See pseudo translation.

Pseudo-translated build

[Ðŕîvîñĝ Ţîɱé ___] PS [Ðŕîvîñĝ ðîšţåñçé: ____] 220 [Šþééð: ___] 88 [Çåļçûļåţé ______________] [Çåļçûļåţé ______________] Driving time is 2 hours 30 minutes Too long and still English (hard-coded)

Validation. Soluling validates translations while you type and in batch (Validation | Validate Translations): missing translations, inconsistent placeholders and patterns, duplicate hotkeys, and more. See validation.

Validation: German

⚠ Inconsistent format string Sport {0} The original has {0}; the translation has no placeholder: Sportart ⚠ Missing translation Speed: The page shows the original text, because the key is the original text.
05

Build: create the resource files and satellite assemblies

Choose Home | Build All. Soluling writes the localized .resx files into the resource folder of the project, such as Resources\Pages\Index.fi.resx, and creates the satellite assemblies, such as fi\RazorDriving.resources.dll, in the output folder. Use the Satellite assembly options and Output sheets to configure them. Because the localized files are now in your project, Visual Studio also builds the satellite assemblies when you build or publish. Deploy them with the main assembly.

Localized resource files and satellite assemblies Soluling writes Index.fi.resx, IndexModel.fi.resx, Index.de.resx, and IndexModel.de.resx into Resources\Pages. The output folder has RazorDriving.dll and fi and de folders, each with RazorDriving.resources.dll. Project DIR Resources\Pages\ RES Index.fi.resx written by Soluling RES IndexModel.fi.resx RES Index.de.resx RES IndexModel.de.resx Build output DIR bin\Release\net9.0\ DLL RazorDriving.dll original, English texts in the code fi fi\RazorDriving.resources.dll de de\RazorDriving.resources.dll
The resource folder is the one you set with AddLocalization, here Resources.
06

Update: translate only what changed

When you change the strings in your code, open the Soluling project and click Home | Scan. Soluling extracts the strings again, keeps the existing translations, and adds the new and changed strings. Because the key is the original text, a changed text is a new string. Translate the new rows and build again. You can run the scan and build steps in your build pipeline with SoluMake.

Reference

The original text is the key

A localizer looks up the text in the resources of the current UI culture. If it finds a translation, it returns it; if not, it returns the key, which is the original text. So the original language needs no resource file at runtime, and only the localized ones are deployed, compiled into satellite assemblies.

To create the localized files, a tool needs the original .resx files as templates, and keeping them up to date by hand is slow and error-prone. Soluling creates them from the source code on every scan, with your comments, so they are always current.

Razor Pages and MVC Web API Blazor
IStringLocalizer Yes Yes Yes
IViewLocalizer Yes No views No
Data annotation localization Yes Yes No
Files that Soluling scans .cshtml, .cs .cs .razor, .cshtml, .cs
Setup file _ViewImports.cshtml _Imports.razor

Culture fallback

.NET looks up each string in the specific culture (fi-FI), then in its parent (fi), and finally falls back to the key, the original text in the code. Add the neutral language, such as Finnish (fi), as the target language.

String lookup for the fi-FI UI culture For UI culture fi-FI, the fi-FI resources are not shipped. Driving Time and Calculate are found in the fi satellite assembly as Ajoaika and Laske. A string that is not translated returns its key, the original text. UI culture: fi-FI fi-FI\ not shipped fi\RazorDriving.resources.dll the key original text in the code Driving Time – ✓ Ajoaika Calculate – ✓ Laske A new string – not translated ✓ A new string

Choose and change the language

Tell the localization where the resource files are, in Program.cs:

builder.Services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

Razor Pages, MVC, and Blazor Server

Add the request localization middleware. Razor Pages and MVC also enable the view and data annotation localizers:

builder.Services.AddRazorPages()   // or AddControllersWithViews() in MVC
  .AddViewLocalization()
  .AddDataAnnotationsLocalization();
...
var supportedCultures = new[] { "en", "de", "fi" };
var options = new RequestLocalizationOptions()
  .SetDefaultCulture(supportedCultures[0])
  .AddSupportedCultures(supportedCultures)
  .AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(options);

To add a language without changing the code, the Driving sample uses app.UseRequestLocalizationWithAvailableLanguages(Assembly.GetExecutingAssembly().Location, "en") from Soluling's ASP.NET library: it detects the deployed satellite assemblies.

The middleware chooses the language of each request in this order: a query string (?culture=fi-FI), a cookie (.AspNetCore.Culture), and the Accept-Language header of the browser. To let the user change the language, set the cookie or pass the query string. In Blazor Server, the culture of the circuit comes from the first request.

Blazor WebAssembly

The application runs in the browser, so it chooses its own language. Store the user's choice in the browser's local storage with small getLanguage and setLanguage JavaScript functions, and set the culture in Program.cs before the application runs:

var host = builder.Build();
var jsInterop = host.Services.GetRequiredService<IJSRuntime>();
var language = await jsInterop.InvokeAsync<string>("getLanguage");
var culture = new CultureInfo(language);
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
await host.RunAsync();

Add <BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData> to the .csproj, so the application has the data of every culture. To change the language, call setLanguage and reload the page with Navigation.NavigateTo(Navigation.Uri, forceLoad: true).

Localized views in MVC

In MVC, you can also localize the view files instead of using a localizer in them. Check HTML resources on the Resources sheet, and Soluling makes localized versions of the .cshtml files, such as Index.fi.cshtml. Your views can then keep hard-coded strings in the markup and scripts. See the Samples\ASP.NET\Core\MVC\DrivingView sample. Razor Pages don't support localized page files, so there the localizer is the only option.

Translate in Soluling Cloud

With Soluling Cloud, translators use Translate in a browser. How you start depends on what you localize:

  • ASP.NET Core and Blazor projects. Soluling Cloud can't scan the source code of a Visual Studio project itself. Translators see your //loc comments in Translate. Create the project in Soluling Desktop, and choose Translate | Configure Cloud to upload it. Use Import from Cloud to get the translations back and build the localized files locally. Your application files never leave your machine.

To run the scan, upload, import, and build steps in your build pipeline, use SoluMake. See the Cloud tutorial and workflows.

Do and don't

Do

  • Use a localizer for every text in .cshtml, .razor, and .cs files.
  • Use numbered placeholders: localizer["... {0} ...", value].
  • Comment strings with //loc, and describe every placeholder.
  • Add the neutral languages, such as fi, as target languages.
  • In Blazor, keep the assembly name and the default namespace the same.
  • Pseudo-translate before the first real translation.

Don't

  • Pass an interpolated string ($"...") to a localizer.
  • Build sentences from pieces in the markup.
  • Write the original .resx files by hand; Soluling creates them.
  • Use MarkupString with user input.
  • Forget BlazorWebAssemblyLoadAllGlobalizationData in Blazor WebAssembly.

Typical localizability problems

See also internationalization and pseudo translation.

Problem How it shows Find and fix
Texts not wrapped with a localizer English text in a pseudo-translated build Use Localizer["..."] or localizer["..."] for the text.
Interpolated strings The string is missing from the project Use localizer["... {0} ...", value] instead of $"...".
Sentences built from pieces Word order and plurals are wrong in the translation Use one string with placeholders, or a plural pattern.
The same text with two meanings One translation for both Pass different types to IStringLocalizer, so the texts are in different resource files.
Fixed widths Clipped text in the pseudo or German build Let the layout grow with the text.

Troubleshooting

Symptom Likely cause What to do
The application stays in English The resource path is wrong, or the satellite assemblies were not deployed Check ResourcesPath in AddLocalization, and deploy the language folders. In Blazor, also make the assembly name and the default namespace the same.
The application ignores the language The request localization middleware is missing or doesn't list the language Add UseRequestLocalization with the language, or UseRequestLocalizationWithAvailableLanguages.
Localizer is not found in a view IViewLocalizer is not injected or enabled Add it to _ViewImports.cshtml, and call AddViewLocalization.
Blazor WebAssembly shows wrong date or number formats The globalization data of the culture is not loaded Add BlazorWebAssemblyLoadAllGlobalizationData.
A Razor class library is not localized Its resource folder is not set Set the resource directory on the source's options; it must have the same name as the application's.
Display names and validation messages of models in a class library stay in English ASP.NET Core looks for their resources in the class library Add an empty SharedResource class to the application and set DataAnnotationLocalizerProvider to factory.Create(typeof(SharedResource)). Soluling then scans the referenced projects too and writes all data annotations into Resources\SharedResource.resx. See Data annotations in class libraries.

Samples

The ASP.NET Core samples are in Samples\ASP.NET\Core of the Soluling installation and on GitHub:

  • RazorPages\Driving and MVC\Driving: the driving time calculator, with strings, images, and plural patterns. Try these first.
  • MVC\DrivingView: as above, with localized view files.
  • MVC\HelloWorld and MVC\Minimal: small localized applications.
  • RazorPages\Sport and WebAPI\SportAPI: a localized application and a multilingual API.

The Blazor samples are in Samples\Blazor and on GitHub:

  • Server\SimpleServer: a simple localized Blazor Server application. Try this first.
  • Server\SportServer: a Blazor Server application that uses a multilingual web API.
  • Server\Multi: localizing a Razor class library.
  • Server\Shared: all pages, components, and classes use one shared resource file.
  • Wasm\SportWasm: a Blazor WebAssembly application that uses a multilingual web API.

See ASP.NET Core localization and Blazor localization in the Desktop documentation for all the details.

FAQ

No. Soluling scans your source code for the localizer calls and creates the original .resx files, by default only in memory, on every scan.

Blazor supports only IStringLocalizer, not IViewLocalizer, IHtmlLocalizer, or data annotation localization. Blazor WebAssembly also chooses its language in the browser. The Soluling project and the localized files are the same. See Choose and change the language.

Yes. In Razor Pages, MVC, and Blazor Server, use a culture cookie or query string parameter. In Blazor WebAssembly, store the language and reload the page.

In MVC, yes. Soluling can make localized versions of the view files. See Localized views in MVC. Razor Pages and Blazor need the localizers.

Yes. Create the project in Soluling Desktop and upload it to Soluling Cloud; translators see your //loc comments in Translate.

Related

All guides