用app.net Core搞掂多国语言网站

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"]
 
测试运行
搞点。
posted @ 2017-05-23 13:23  王伟晔  阅读(1176)  评论(5编辑  收藏  举报