Json Localizer library for .NET ASP.NET Core projects.
This is a maintained fork of AspNetCore.Localizer.Json with critical bug fixes.
The original library has critical bugs that cause localization to fail:
-
Cache key missing culture - Cache was keyed by resource name only. Once cached in one culture, wrong translations were returned for other cultures.
-
Culture resolution priority - Used
DefaultThreadCurrentUICulture ?? CurrentUICulture, causing the process-wide default to override per-request culture set byRequestLocalizationMiddleware. -
Culture state corruption on cache hit - When switching to a previously-cached culture,
_currentCulturewas not updated, causing subsequent lookups to return wrong translations.
All issues are now fixed.
From version 1.0.0, the library uses only EmbeddedResource to load the files.
This library allows users to use JSON files instead of RESX in an ASP.NET application. The code tries to be most compliant with Microsoft guidelines. The library is compatible with NetCore.
An extension method is available for IServiceCollection.
You can have a look at the
method here
A set of options is available. You can define them like this :
services.AddJsonLocalization(options => {
options.CacheDuration = TimeSpan.FromMinutes(15);
options.ResourcesPath = "mypath";
options.FileEncoding = Encoding.GetEncoding("ISO-8859-1");
options.SupportedCultureInfos = new HashSet<CultureInfo>()
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
options.AssemblyHelper = new AssemblyHelper("MyAssembly");
});- SupportedCultureInfos : _Default value : List containing only default culture and CurrentUICulture. Optionnal array of cultures that you should provide to plugin. _(Like RequestLocalizationOptions)
- ResourcesPath : Default value :
$"{_env.WebRootPath}/Resources/". Base path of your resources. The plugin will browse the folder and sub-folders and load all present JSON files. - AdditionalResourcesPaths : Default value : null. Optionnal array of additional paths to search for resources.
- UseEmbeddedResources : default value: true. When set to
false, JSON files are loaded directly from the file system instead of from embedded resources. - CacheDuration : Default value : 30 minutes. We cache all values to memory to avoid loading files for each request, this parameter defines the time after which the cache is refreshed.
- FileEncoding : default value : UTF8. Specify the file encoding.
- Caching : _default value: MemoryCache. Internal caching can be overwritted by using custom class that extends IMemoryCache.
- PluralSeparator : _default value: |. Seperator used to get singular or pluralized version of localization. More information in Pluralization
- MissingTranslationLogBehavior : _default value: LogConsoleError. Define the logging mode
- LocalizationMode : _default value: Basic. Define the localization mode for the Json file. Currently Basic and I18n. More information in LocalizationMode
- MissingTranslationsOutputFile : This enables to specify in which file the missing translations will be written
when
MissingTranslationLogBehavior = MissingTranslationLogBehavior.CollectToJSON, defaults toMissingTranslations-<locale>.json - IgnoreJsonErrors: This properly will ignore the JSON errors if set to true. Recommended in production but not in development.
- LocalizerDiagnosticMode: When set to true, the localizer will replace all localized with "X". This is designed to identify text that is not using the localizer on the page.
- AssemblyHelper: This is used to load the resources from a specific assembly. If not set, the plugin will use the entry assembly.
To be able to load culture files from an assembly, you should use set WithCulture="false" in csproj file.
<ItemGroup>
<EmbeddedResource Include="Resources\localization.json" WithCulture="false">
</EmbeddedResource>
<EmbeddedResource Include="i18n\*.json" WithCulture="false">
</EmbeddedResource>
</ItemGroup>You are now able to manage a singular (left) and plural (right) version for the same Key. PluralSeparator is used as separator between the two strings.
For example : User|Users for key Users
To use plural string, use parameters from IStringLocalizer, if last parameters is a boolean, pluralization will be activated.
Pluralization is available with IStringLocalizer, IViewLocalizer and HtmlStringLocalizer :
You can have multiple pluralization, to use it, you should
use IJsonStringLocalizer interface and this method
LocalizedString GetPlural(string key, double count, params object[] arguments)
localizer.GetString("Users", true);
We allows you to clean cache. It's usefull when you want's tu update in live some translations.
Example
public class HomeController{
private readonly IJsonStringLocalizer _localizer;
public HomeController(IJsonStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
_localizer.ClearMemCache(new List<CultureInfo>()
{
new CultureInfo("en-US")
});
}
}As you know, Blazor Server does not provide IHtmlLocalizer. To avoid this, you can now use
from IJsonStringLocalizer this method
MarkupString GetHtmlBlazorString(string name, bool shouldTryDefaultCulture = true)
Platform Support
| Platform | Version |
|---|---|
| NetCore | 9.0.0+ |
| Blazor Server | 9.0.0+ |
| Blazor Wasm | 9.0.0+ |
| Blazor MAUI | 9.0.0+ |
As asked on the request #64, Some user want to have the possiblities to manage file with i18n way. To answer this demand, a localization mode was introduced with default value Basic. Basic version means the the one describe in the previous parts
To use the i18n file management, use the the option Localization mode like this :
cs LocalizationMode = LocalizationMode.I18n.
After that, you should be able to use this json :
{
"Name": "Name",
"Color": "Color"
}File name
File name are important for some purpose (Culture looking, parent culture, fallback).
Please use this pattern : [fileName].[culture].json If you need a fallback culture that target all culture, you can create a file named localisation.json. Of course, if this file does not exist, the chosen default culture is the fallback.
After talking with others Devs about my package, they asked my about performance.
BenchmarkDotNet v0.14.0, EndeavourOS
AMD Ryzen 9 7950X3D, 1 CPU, 32 logical and 16 physical cores
.NET SDK 9.0.100
[Host] : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
DefaultJob : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI| Method | Mean | Error | StdDev | Min | Max | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Localizer | 31.83 ns | 0.140 ns | 0.117 ns | 31.62 ns | 32.00 ns | 1.00 | 0.01 | - | - | - | NA |
| JsonLocalizer | 11.70 ns | 0.030 ns | 0.027 ns | 11.67 ns | 11.75 ns | 0.37 | 0.00 | - | - | - | NA |
| JsonLocalizerWithCreation | 140,762.12 ns | 2,813.586 ns | 5,810.543 ns | 126,991.04 ns | 150,169.03 ns | 4,422.62 | 181.61 | 3.9063 | 3.4180 | 203362 B | NA |
| I18nJsonLocalizerWithCreation | 87,809.74 ns | 285.333 ns | 238.266 ns | 87,211.17 ns | 88,223.01 ns | 2,758.90 | 12.16 | 9.7656 | 9.5215 | 166091 B | NA |
| JsonLocalizerWithCreationAndExternalMemoryCache | 4,411.59 ns | 63.052 ns | 58.979 ns | 4,301.21 ns | 4,500.86 ns | 138.61 | 1.86 | 0.1373 | 0.1297 | 7144 B | NA |
| JsonLocalizerDefaultCultureValue | 76.77 ns | 1.097 ns | 0.857 ns | 74.63 ns | 77.90 ns | 2.41 | 0.03 | 0.0129 | - | 216 B | NA |
| MicrosoftLocalizerDefaultCultureValue | 108.21 ns | 1.132 ns | 1.059 ns | 106.70 ns | 110.48 ns | 3.40 | 0.03 | 0.0043 | - | 216 B | NA |
|
Michael Monsour |
Luka Gospodnetic |
Christoph Sonntag |
Nacho |
Ashley Medway |
Serhii Voitovych |
James Hill |
Ferenc Czirok |
rohanreddyg |
rickszyr |
ErikApption |
A special thanks to @Compufreak345 for is hard work. He did a lot for this repo.
A special thanks to @EricApption for is work to improve the repo and making a very good stuff on migrating to net6 and
System.Text.Json & making it working for blazor wasm