Press "Enter" to skip to content

Solving Blazor localization problem

magnus 0

Essentials

Localization in Blazor i simple enough (see https://docs.microsoft.com/en-us/aspnet/core/blazor/globalization-localization?view=aspnetcore-5.0).

  1. Addservices.AddLocalization(options => options.ResourcesPath = "Resources");to Startup.cs
  2. Create the folder Resources and add "resources" files to it.
    • Create page specific files under the Resources/Pages folder, e.x. Resources/Pages/Index.resx.
    • You can add common translations to e.g. Resources/App.resx.
  3. Use IStringLocalizer in your razor files:

@inject IStringLocalizer<App> GlobalLocalizer
@inject IStringLocalizer<Index> Localizer

<h1>@GlobalLocalizer["site.name"]</h1>
<div>
    @Localizer["introduction"]
</div>

Changing locale

See Microsofts guide for this: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-5.0.

Irritating problem

Initially, I couldn't get this to work. I tried many things, renaming and moving .resx files around and trying out Custom Tool setting ResXFileCodeGenerator, to no avail.

Everything pointed to a problem with paths to resources files and in a desperate attempt, I skipped the Resources folder and put the resources files next to their razor files:

services.AddLocalization(options => options.ResourcesPath = "");

MyServiceBlazor/
  App.razor
  App.resx
  Pages/
    Index.razor
    Index.resx

This worked, but code base felt clogged and Visual Studio tooling didn't recognize the files and gave no support.

Solution

The reason for all of this was that the project name ("MyServiceBlazor") was different from the RootNamespace ("MyService") setting in the .csproj file.

 <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>MyService</RootNamespace>
  </PropertyGroup>

Renaming the .csproj file to match the RootNamespace solved the issue and I could use the desired Resources approach:

MyServiceBlazor.csproj -> MyService.csproj.

MyService/
  App.razor
  Pages/
    Index.razor
  Resources/
    App.resx
    App.sv-SE.resx
    Pages/
      Index.resx
      Index.sv-SE.resx