文章出處

首先在 Startup 的 ConfigureServices 中添加 AddLocalization 與 AddViewLocalization 以及配置 RequestLocalizationOptions (這里假設使用英文與中文):

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() 方法中應用 RequestLocalizationOptions :

var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(requestLocalizationOptions);

然后在 _Layout.cshtml 視圖中通過 IViewLocalizer 接口以多語言的方式顯示頁面標題的后綴:

@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 項目中創建 Resources 文件夾,在其中分別添加 Views.Shared._Layout.en-Us.resx 與 Views.Shared._Layout.zh-CN.resx 文件, Views.Shared._Layout.resx 文件,并添加 "SiteTitle" 所對應的語句文字:

1)Views.Shared._Layout.en-Us.resx

2)Views.Shared._Layout.zh-CN.resx

這時運行 ASP.NET Core 站點,就會根據瀏覽器的語言設置(Accept-Language header)、或者 culture 查詢參數、或者 .AspNetCore.Culture Cookie 值顯示對應語言的文字:

需要注意的地方:千萬不要添加不帶語言名稱的 Views.Shared._Layout.en-Us.resx ,不然添加代碼語言名稱的 .resx 文件時會遇到  "Custom tool ResXFileCodeGenerator failed to produce an output for input file ... but did not log a specific error." 問。

一定要看的參考文檔:Globalization and localization 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()