Asp.net Core 中文文檔不多,你能夠看英文的,不過英文的也是說的有點亂。這篇文章是乾貨。
1. 配置好你的WebApplication,使他能夠支持國際化語言,修改文檔Startup.cs
public
void
ConfigureServices(
IServiceCollection
services)
{
services.AddLocalization(options => options.ResourcesPath =
"Resources"
);
services.AddMvc()
.AddViewLocalization(
LanguageViewLocationExpanderFormat
.Suffix)
.AddDataAnnotationsLocalization();
}
2.修改好你的配置
public
void
Configure(
IApplicationBuilder
app,
IHostingEnvironment
env,
ILoggerFactory
loggerFactory)
{...
這裏面寫你的網站須要支持的語言。
var
supportedCultures =
new
[]
{
new
CultureInfo
(
"en-US"
),
new
CultureInfo
(
"zh-CN"
)
};
這裏是寫你的默認語言的
app.UseRequestLocalization(
new
RequestLocalizationOptions
{
DefaultRequestCulture =
new
RequestCulture
(
"en-US"
),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
}
3.給你的視圖增長資源文檔
a.增長Resources目錄
b.按你的視圖路徑,給出資源文檔的結構 例如你的視圖Views\Home\Index.cshtml 你的資源Resources\Views\Home\Index.zh-CN.resx 或 Resources\Views\Home\Index.en-US.resx
c.在資源文件中添加Key 和Value
d.視圖頂部
@
using
Microsoft.AspNetCore.Mvc.Localization
@inject
IViewLocalizer
Localizer
須要顯示的字符串中
將
Learn More 修改
@Localizer[
"Learn More"
]
測試運行
搞點。