我浪费了大量时间筛选有关如何本地化 Razor Pages 的不完整解释,经常发现答案与 MVC 有关。因此,让我为您节省所有时间,并为您提供对我有用的简单步骤。我不会假装知道为什么需要任何东西的细节,只是知道它有效。
将 Microsoft.Extensions.Localization nuGet 包添加到项目中。
到_ViewImports.cshtml,添加:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
services.AddRazorPages();
到
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>
我正在对 Razor 页面执行类似的操作,并且每种语言都有一个文件,其中包含所有资源字符串/图像,即我的文件的命名类似于
Res.resx
Res.da.resx
Res.es.resx
program.cs看起来像这样:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddRazorPages()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
/* Enable support for localized DataAnnotations validation
messages.
NB: this works in .NET 7.0
*/
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (_, factory) =>
{
var assemblyName = new AssemblyName(typeof(Res).GetTypeInfo().Assembly.FullName!);
return factory.Create(nameof(Res), assemblyName.Name!);
};
});
...
文件夹结构:
.resx的属性:
将字符串
PublicResXFileCodeGenerator
添加到仅主资源文件的 Custom Tool property
中非常重要,即 Res.resx
让 Visual Studio 生成 Res.Designer.cs
类。
用法:
我不使用
@Localizer["PrivacyPolicy"]
,而是使用@Res.PrivacyPolicy
。请参阅下面的示例: