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.
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.csfiles - Output
- Localized
.resxfiles (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
- How the localization works
- Culture fallback
- Choose and change the language
- Localized views in MVC
- Translate in Soluling Cloud
- Do and don't
- Typical localizability problems
- Troubleshooting
- Samples
- FAQ
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.
Prepare: use a localizer for every text
These rules are the same everywhere:
-
The text is the key. Write
localizer["Enter values and click Calculate."]instead of the text. You don't create a.resxfile. Each type you pass toIStringLocalizer<T>gets its own resource file; pass the same type everywhere to have only one. -
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. -
Comment the strings. A
//loccomment on the same line in C# code is shown to the translator, for example,//loc 0: Hours or minutes. -
Use plural patterns for numbers. The Driving sample passes its plural pattern through the localizer and formats it with
MultiPattern.FormatMultifrom 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.Localizationand@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, andErrorMessageto 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.Localizationto_Imports.razor. Blazor WebAssembly also needs theMicrosoft.Extensions.LocalizationNuGet package. -
Blazor supports only
IStringLocalizer: add@inject IStringLocalizer<Index> localizerto 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.
@localizer from IStringLocalizer.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
.resxfiles, 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
.resxfiles. - 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.
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.
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
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
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.
AddLocalization, here Resources.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.
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.
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
//loccomments 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.csfiles. - 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
.resxfiles by hand; Soluling creates them. - Use
MarkupStringwith user input. - Forget
BlazorWebAssemblyLoadAllGlobalizationDatain 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
.resx files, by default only in memory, on every scan.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.//loc comments in Translate.Related
- ASP.NET Core localization - the full Desktop documentation
- Blazor localization - the full Desktop documentation
- ASP.NET Framework localization - the older framework, which works differently
- Supported formats - everything else Soluling localizes