首先在 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. 问。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。