有关ASP.NET Core 中的多语言支持的详细介绍


本文摘自PHP中文网,作者巴扎黑,侵删。

本篇文章主要介绍了ASP.NET Core 中的多语言支持(Localization) ,具有一定的参考价值,有兴趣的可以了解一下

首先在 Startup 的 ConfigureServices 中添加 AddLocalization 与 AddViewLocalization 以及配置 RequestLocalizationOptions (这里假设使用英文与中文):


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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 :


1

2

var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;

app.UseRequestLocalization(requestLocalizationOptions);

然后在 _Layout.cshtml 视图中通过 IViewLocalizer 接口以多语言的方式显示页面标题的后缀:


1

2

3

4

5

6

7

8

9

10

@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 中的多语言支持的详细介绍的详细内容!

相关阅读 >>

asp.net mvc 设置生成pdf文件,并可以点击预览

asp.net怎么使用js文件

asp.net是什么意思?asp.net框架的特性有哪些

使用action的模型绑定实例教程

如何在不使用 webmatrix 的情况下发布 web pages?

.net core + angular cli 实现开发环境搭建

图文详解asp.net百度ueditor编辑器实现上传图片添加水印效果实例

asp.net实现省市二级联动功能的实例代码

.net中core如何利用redis发布订阅的实例分析

.net core配置与自动更新的实现方法_实用技巧

更多相关阅读请进入《asp.net》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...