JSON Localization Resources for ASP.NET Core 2.0 and 3.0
Use these instructions to get the package and use it.
From the command prompt
dotnet add package Mohmd.JsonResourcesor
Install-Package Mohmd.JsonResourcesor
paket add Mohmd.JsonResourcesAdd service
public void ConfigureServices(IServiceCollection services)
{
// We can also use appsettings.json to configure options.
services.AddJsonLocalization(options =>
{
options.ResourcesPath = "Resources"; // based on project's root
options.GlobalResourceFileName = "global";
options.AreasResourcePrefix = "areas";
options.SetDefaultCultureCookie = true;
});
services.AddMvc()
.AddViewLocalization(); // add this line to enable localization in views
}Then add the middleware
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IOptions<RequestLocalizationOptions> localizationOptions)
{
// Localization
app.UseJsonLocalizer();
app.UseRequestLocalization(localizationOptions.Value);
app.UseMvc();
}{
"key": "locale",
"group.key": "something"
}There are 3 general ways to add locale resources to your projects.
- Single Global json file
- One json file per Area
- One json file for every single file in the project
We can use all of along side each other.
Create global.json (or whatever you set
in options.GlobalResourceFileName) in root of resources directory.
global.json
global.fa-IR.json
global.de-DE.json
Create a json file for every area you have.
For example if you have "Admin" area, and options.AreasResourcePrefix is set to 'Area',
then json file would be Area.Admin.json
Area.Admin.json
Area.Admin.fa-IR.json
Area.Admin.de-DE.json
Every .cs or .cshtml file needs a json resource.
Naming follows default xml based localization in ASP.NET Core.
So if we have a file like this: Views/Home/Index.cshtml. Resource file can be one of these:
Resources/Views/Home/Index.json
Resources/Views/Home.Index.json
Resources/Views.Home.Index.json
Resources/Views.Home.Index.fa-IR.json
Resources/Views.Home.Index.de-DE.json
This project originally created by @hishamco (repo).
I've made a few changes on it, and used it for a long time.