3d萌系跳舞游戏,孙海晨,拜托了冰箱第三季嘉宾
上次我们提到了,微软默认提供基于资源文件的多语言本地化,个人感觉使用起来不是太方便,没有 json 看起来直观,于是动手造了一个轮子, dotnet core 基于 json 的本地化组件
需要引用 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~
for types:
home/index
=> controllers/homecontroller
资源路径:
示例:
for razor 视图:
示例:
for types:
home/index
=> controllers/homecontroller
资源路径:
示例:
for razor 视图:
示例:
copy your resource files to output:
需要设置将资源文件拷贝到输出目录,否则会找不到资源文件,可以在启动项目项目文件中加入以下示例代码:
<itemgroup> <content update="resources\**\*.json"> <copytooutputdirectory>always</copytooutputdirectory> </content> </itemgroup>
上面的配置会将 resources
目录下的所有 json 文件拷贝到输出目录下,可以根据自己的需要进行修改
用法和之前是一样的
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": "中文" }
扩展增加了 culturebased
方式,这样就方便将某一种语言的语言包打包,也方便了扩展,支持其他语言的时候只需要导入一个其他语言的语言包即可
在线示例:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论