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.
Add the Microsoft.Extensions.Localization nuGet package to the project.
To _ViewImports.cshtml, add:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
services.AddRazorPages();
to
services.AddLocalization( options => options.ResourcesPath = "Resources" );
services.AddRazorPages()
.AddViewLocalization();
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 );
<h2>@Localizer["Hello"]</h2>
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="Hello" xml:space="preserve">
<value>Bonjour</value>
</data>
</root>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With