.NET Core 的多國語系套件是 Microsoft.Extensions.Localization,再透過 IStringLocalizer<T> 物件來取得資源檔內容,預設整合了資源檔,上篇介紹了 Tolgee 管理多國語系,它支援了 i18n 的檔案,這篇將記錄使用 I18Next.Net 的方式,再來想辦法將它們整合。
更多內容請參考:https://learn.microsoft.com/zh-tw/dotnet/core/extensions/localization
開發環境
- Windows 11 Home
- ASP.NET Core 8
- Rider 2024.2
- I18Next.Net
實作
新增 Web API 專案,安裝 I18Next.Net
dotnet add package I18Next.Net --version 1.0.0
配置 DI Container
- 語系檔位置:new JsonFileBackend("wwwroot/locales")
- 預設語言:options.DefaultLanguage = "en";
- namespace:options.DefaultNamespace = "translation";
builder.Services.AddI18NextLocalization(i18N =>
{
i18N.Configure(options =>
{
options.DefaultNamespace = "translation";
options.DefaultLanguage = "en";
options.FallbackLanguages = new[] { "en" };
});
i18N.IntegrateToAspNetCore()
.AddBackend(new JsonFileBackend("wwwroot/locales"))
;
});
語系檔結構
語系檔內容
{
"page": {
"title": "This is a translated page title"
},
"about": {
"description": "This is the description of your about page.",
"renderedOn": "This page was rendered on {{date, yyyy/mm/dd}}.",
"additionalInformation": "additional information",
"infoText": "Use this area to provide $t(about.additionalInformation)."
}
}
設定 RequestLocalizationOptions
使服務可以根據文化特性切換語系
app.UseRequestLocalization(p =>
{
// var supportedCultures = new[] { "en-US", "de-DE", "zh-TW" };
var supportedCultures = new[] { "en", "de", "zh" };
var cultureInfos = supportedCultures.Select(c => new CultureInfo(c)).ToList();
p.DefaultRequestCulture = new RequestCulture(supportedCultures[1]);
p.SupportedCultures = cultureInfos;
p.SupportedUICultures = cultureInfos;
});
依賴 IStringLocalizer
在需要支援多國語系的地方開一個洞,讓它依賴 IStringLocalizer<DemoController> localizer
取出語系內容:localizer["about.description"]
更多內容請參考:https://learn.microsoft.com/zh-tw/aspnet/core/fundamentals/localization/make-content-localizable
[ApiController]
public class DemoController(IStringLocalizer<DemoController> localizer) : ControllerBase
{
[HttpGet]
[Route("api/v1/demo", Name = "GetDemo")]
public IActionResult Get()
{
var desc = localizer["about.description"];
return Ok(new
{
desc,
});
}
}
切換語系
RequestLocalizationOptions 預設的切換語系有這三種方式:
- QueryStringRequestCultureProvider
- CookieRequestCultureProvider
- AcceptLanguageHeaderRequestCultureProvider
更多內容參考:https://learn.microsoft.com/zh-tw/aspnet/core/fundamentals/localization/select-language-culture
QueryString
https://localhost:7296/api/v1/demo?culture=zh
Accept-Language Header
curl --location 'https://localhost:7296/api/v1/demo' `
--header 'Accept-Language: zh'
範例位置
sample.dotblog/i18N at 2b19517d589457fa72a2cdd9319e400ee00a9037 · yaochangyu/sample.dotblog
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET