源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

详解ASP.NET Core 中的多语言支持(Localization)

  • 时间:2022-12-16 18:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:详解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 [img]http://files.jb51.net/file_images/article/201708/201708301053331.png[/img] 2)Views.Shared._Layout.zh-CN.resx [img]http://files.jb51.net/file_images/article/201708/201708301053332.png[/img] 这时运行 ASP.NET Core 站点, 就会根据浏览器的语言设置(Accept-Language header)、或者 culture 查询参数、或者 .AspNetCore.Culture Cookie 值显示对应语言的文字: [img]http://files.jb51.net/file_images/article/201708/201708301053333.png[/img] [img]http://files.jb51.net/file_images/article/201708/201708301053344.png[/img] 需要注意的地方:千万不要添加不带语言名称的 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." 问。 一定要看的参考文档:[url=https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization]Globalization and localization  [/url] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部