引用包
添加对 OrchardCore.Localization.Core NuGet 包的引用。
注册服务
将所需服务添加到 Startup.cs 的 ConfigureServices 方法:
public void ConfigureServices (IServiceCollection services) {
services.AddMvc ()
.AddViewLocalization (LanguageViewLocationExpanderFormat.Suffix);
services.AddPortableObjectLocalization ();
services.Configure<RequestLocalizationOptions> (options => {
var supportedCultures = new List<CultureInfo> {
new CultureInfo ("en-US"),
new CultureInfo ("en"),
new CultureInfo ("fr-FR"),
new CultureInfo ("fr")
};
options.DefaultRequestCulture = new RequestCulture ("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
}
将所需中间件添加到 Startup.cs 的 Configure 方法:
public void Configure (IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment ()) {
app.UseDeveloperExceptionPage ();
app.UseBrowserLink ();
} else {
app.UseExceptionHandler ("/Home/Error");
}
app.UseStaticFiles ();
// 配置请求区域
app.UseRequestLocalization ();
app.UseMvcWithDefaultRoute ();
}
将以下代码添加到所选的 Razor 视图中。 在此示例中,使用了 About.cshtml。
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<p> @Localizer["Hello world!"] </p>
创建 PO 文件
在应用程序根文件夹中创建名为 语言(如:en)+.po 的文件
在此示例中,文件名为 fr.po,因为使用了法语:
msgid “Hello world!”
msgstr “Bonjour le monde!”
此文件存储了要转换的字符串和已转换为法语的字符串。
测试应用程序
运行应用程序并导航到 URL /Home/About。 此时将显示文本 Hello world! 。
导航到 URL /Home/About?culture=fr-FR。 此时将显示文本 Bonjour le monde! 。