首先在 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中的多言语支持的图文详解的细致内容,更多请关注ki4网别的相干文章!