用app.net Core搞掂多國語言網站

王偉曄發表於2017-05-23
Asp.net Core 中文文件很少,你可以看英文的,不過英文的也是說的有點亂。這篇文章是乾貨。
1. 配置好你的WebApplication,使他可以支援國際化語言,修改文件Startup.cs
        publicvoid 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"]
 
測試執行
搞點。

相關文章