25

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

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzAxMjE2NTMxMw%3D%3D&%3Bmid=2456606066&%3Bidx=1&%3Bsn=5acbe18dee5164a09ee42c0b61b873a2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

Intro

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

GetStarted

需要引用 nuget 包 WeihanLi.Extensions.Localization.Json

注册服务:

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

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:

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

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

Use

用法和之前是一样的

Controller 示例:

Razor 视图示例:

资源文件示例:

Samples

  • AspNetCore3.1 Basic Sample

  • ActivityReservation


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK