首頁  >  文章  >  後端開發  >  有關ASP.NET Core 中的多語言支援的詳細介紹

有關ASP.NET Core 中的多語言支援的詳細介紹

巴扎黑
巴扎黑原創
2017-09-01 14:23:121341瀏覽

本篇文章主要介紹了ASP.NET Core 中的多語言支援(Localization) ,具有一定的參考價值,有興趣的可以了解一下

首先在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." 問

以上是有關ASP.NET Core 中的多語言支援的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn