ASP.NET Core中的多語言支援的圖文詳解

來源:互聯網
上載者:User
本篇文章主要介紹了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." 問。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.