.net core 实现基于 json 的多语言

intro

上次我们提到了,微软默认提供基于资源文件的多语言本地化,个人感觉使用起来不是太方便,没有 json 看起来直观,于是动手造了一个轮子, dotnet core 基于 json 的本地化组件

getstarted

需要引用 nuget 包 weihanli.extensions.localization.json

注册服务:

services.addjsonlocalization(options =>
    {
        options.resourcespath = configuration.getappsetting("resourcespath");
        options.resourcespathtype = resourcespathtype.typebased; // 默认方式和微软找资源的方式类似
        // options.resourcespathtype = resourcespathtype.culturebased; // 在对应的 culture 子目录下寻找资源文件,可以参考后面的示例
    });

中间件配置(如果是asp.net core,和之前一样):

app.userequestlocalization();

that’s it~

添加你的资源文件

typebased 资源文件的路径

for types:

home/index => controllers/homecontroller

资源路径:

  • [resourcespath]/controllers/homecontroller.[culturename].json

示例:

  • resources/controllers/homecontroller.en.json
  • resources/controllers/homecontroller.zh.json

for razor 视图:

示例:

  • resources/views/home/index.en.json
  • resources/views/home/index.zh.json

culturebased 资源文件路径

for types:

home/index => controllers/homecontroller

资源路径:

  • [resourcespath]/[culturename]/controllers/homecontroller.json

示例:

  • resources/en/controllers/homecontroller.json
  • resources/zh/controllers/homecontroller.json

for razor 视图:

示例:

  • resources/en/views/home/index.json
  • resources/zh/views/home/index.json

copy your resource files to output:

需要设置将资源文件拷贝到输出目录,否则会找不到资源文件,可以在启动项目项目文件中加入以下示例代码:

<itemgroup>
<content update="resources\**\*.json">
    <copytooutputdirectory>always</copytooutputdirectory>
</content>
</itemgroup>

上面的配置会将 resources 目录下的所有 json 文件拷贝到输出目录下,可以根据自己的需要进行修改

use

用法和之前是一样的

controller 示例:

public class valuescontroller : controller
{
    private readonly istringlocalizer<valuescontroller> _localizer;

    public valuescontroller(istringlocalizer<valuescontroller> localizer)
    {
        _localizer = localizer;
    }

    // get: api/<controller>
    [httpget]
    public string get()
    {
        return _localizer["culture"];
    }
}

razor 视图示例:

@using microsoft.aspnetcore.mvc.localization
@using microsoft.extensions.localization
@using weihanli.extensions.localization.json.sample.controllers
@inject ihtmllocalizer<homecontroller> htmllocalizer
@inject istringlocalizer<homecontroller> stringlocalizer
@inject iviewlocalizer viewlocalizer
@{
    viewdata["title"] = "index";
}

<h2>index</h2>

<div>string: @stringlocalizer["hello"]</div>

<div>html: @htmllocalizer["hello"]</div>

<div>view: @viewlocalizer["hello"]</div>

资源文件示例:

{
  "culture": "中文"
}

samples

  • aspnetcore3.1 basic sample
  • activityreservation

more

扩展增加了 culturebased 方式,这样就方便将某一种语言的语言包打包,也方便了扩展,支持其他语言的时候只需要导入一个其他语言的语言包即可

在线示例: