.net core 實現基於 JSON 的多語言
阿新 • • 發佈:2020-01-17
.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
方式,這樣就方便將某一種語言的語言包打包,也方便了擴