Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Localization of Razor Pages

I wasted a lot of time sifting through incomplete explanations of how to localize Razor Pages, often discovering that answers were about MVC. So let me save you all that time, and just give you the simple steps that worked for me. I don't pretend to know the details of why anything is needed, just that it worked.

like image 761
uncaged Avatar asked Sep 18 '25 05:09

uncaged


1 Answers

  1. Add the Microsoft.Extensions.Localization nuGet package to the project.

  2. To _ViewImports.cshtml, add:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
  1. In Startup.cs, change
services.AddRazorPages();

to

services.AddLocalization( options => options.ResourcesPath = "Resources" );
services.AddRazorPages()
    .AddViewLocalization();
  1. Add the supported languages in Startup.cs, by inserting something like the following before app.UseHttpsRedirection():
var supportedCultures = new List<CultureInfo>
{
    new CultureInfo( "en-US" ),
    new CultureInfo( "fr" )
};
var options = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture( "en-US" ),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
};
app.UseRequestLocalization( options );
  1. Add localization to your pages, like:
<h2>@Localizer["Hello"]</h2>
  1. To the web project, add a folder named Resources, with a subdirectory named Pages. In Resources/Pages, add resource files matching the names of the pages to localize. For example, Index.fr.resx:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <data name="Hello" xml:space="preserve">
        <value>Bonjour</value>
    </data>
</root>
  1. Test your localization by adding a query string, such as during debugging changing your URL to https://localhost:5001/?culture=fr
like image 62
uncaged Avatar answered Sep 22 '25 15:09

uncaged