体验 ASP.NET Core 中的多语言支持(Localization)
首先在 Startup 的?ConfigureServices 中添加?AddLocalization 與?AddViewLocalization 以及配置?RequestLocalizationOptions (這里假設(shè)使用英文與中文):
public void ConfigureServices(IServiceCollection services)
{
? ? services.AddLocalization(options => options.ResourcesPath = "Resources");
? ? services.AddMvc()
? ? ? ? .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
? ? services.Configure<RequestLocalizationOptions>(
? ? ? ? opts =>
? ? ? ? {
? ? ? ? ? ? var supportedCultures = new List<CultureInfo>
? ? ? ? ? ? {
? ? ? ? ? ? ? ? new CultureInfo("en-US"),
? ? ? ? ? ? ? ? new CultureInfo("zh-CN")
? ? ? ? ? ? };
? ? ? ? ? ? opts.SupportedCultures = supportedCultures;
? ? ? ? ? ? opts.SupportedUICultures = supportedCultures;
? ? ? ? });
}
在 Startup 的?Configure() 方法中應(yīng)用?RequestLocalizationOptions :
var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value; app.UseRequestLocalization(requestLocalizationOptions);然后在 _Layout.cshtml 視圖中通過(guò)?IViewLocalizer 接口以多語(yǔ)言的方式顯示頁(yè)面標(biāo)題的后綴:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<!DOCTYPE html>
<html>
<head>
? ? <title>@ViewData["Title"] - @Localizer["SiteTitle"]</title>
</head>
<body>
</body>
</html>
接著在 ASP.NET Core Web 項(xiàng)目中創(chuàng)建 Resources 文件夾,在其中分別添加 Views.Shared._Layout.en-Us.resx 與?Views.Shared._Layout.zh-CN.resx 文件,?Views.Shared._Layout.resx 文件,并添加 "SiteTitle" 所對(duì)應(yīng)的語(yǔ)句文字:
1)Views.Shared._Layout.en-Us.resx
2)Views.Shared._Layout.zh-CN.resx
這時(shí)運(yùn)行 ASP.NET Core 站點(diǎn),就會(huì)根據(jù)瀏覽器的語(yǔ)言設(shè)置(Accept-Language header)、或者 culture 查詢參數(shù)、或者?.AspNetCore.Culture Cookie 值顯示對(duì)應(yīng)語(yǔ)言的文字:
需要注意的地方:千萬(wàn)不要添加不帶語(yǔ)言名稱的?Views.Shared._Layout.en-Us.resx ,不然添加代碼語(yǔ)言名稱的 .resx 文件時(shí)會(huì)遇到??"Custom tool ResXFileCodeGenerator failed to produce an output for input file ... but did not log a specific error." 問(wèn)。
一定要看的參考文檔:Globalization and localization?
原文地址:http://www.cnblogs.com/dudu/p/7449375.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺(tái)或掃描二維碼關(guān)注
總結(jié)
以上是生活随笔為你收集整理的体验 ASP.NET Core 中的多语言支持(Localization)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: asp.net core 2.0 web
- 下一篇: ASPNET Core 2.x中的Kes