20 min read

Implementing Custom JSON Localization in ASP.NET Core Web API


In today’s globalized world, supporting multiple languages in web applications is crucial. While ASP.NET Core provides built-in support for localization using .resx files, some developers might prefer a more flexible and modern approach using JSON files. This article demonstrates how to implement custom localization in an ASP.NET Core Web API using JSON files, offering an alternative to the traditional .resx approach.

Overview

The process involves creating JSON files for each supported language, implementing a custom localization service to read these files, and integrating this service into your ASP.NET Core application. This approach not only simplifies the management of localized text but also integrates seamlessly with modern web technologies.

Step 1: Setting Up JSON Localization Files

Creating JSON Files

  1. Organize Your Files: Create a directory named ‘Localizations’ in your project root.
  2. Create Language-Specific Files: For each language, create a JSON file named according to the culture code. For example:
  • Messages.en-US.json
  • Messages.hi-IN.json

Example JSON Structure

Here’s how you might structure the JSON for English and Hindi:

Messages.en-US.json
{
  "Hello": "Hello",
  "Welcome": "Welcome to our application"
}
Messages.hi-IN.json
{
  "Hello": "नमस्ते",
  "Welcome": "हमारे आवेदन में आपका स्वागत है"
}

Step 2: Implementing the Custom Localization Service

Define the Interface and Service

Create an interface IJsonStringLocalizer and a concrete implementation JsonStringLocalizer that will load and manage the localized strings from the JSON files.

public interface IJsonStringLocalizer
{
    string this[string key] { get; }
}

public class JsonStringLocalizer : IJsonStringLocalizer
{
    private Dictionary<string, string> _localizations;

    public JsonStringLocalizer(string filePath)
    {
        var jsonContent = File.ReadAllText(filePath);
        _localizations = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent);
    }

    public string this[string key] => _localizations.ContainsKey(key) ? _localizations[key] : key;
}

Register the Localization Service

Configure the service in your Startup.cs or Program.cs, ensuring it selects the correct language file based on the current culture.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IJsonStringLocalizer>(provider =>
    {
        var env = provider.GetService<IWebHostEnvironment>();
        var lang = CultureInfo.CurrentCulture.Name; // Replace with dynamic culture logic if necessary
        var filePath = Path.Combine(env.ContentRootPath, $"Localizations/Messages.{lang}.json");
        return new JsonStringLocalizer(filePath);
    });

    services.AddControllers();
}

Step 3: Using the Localization Service in Controllers

Inject the IJsonStringLocalizer into your controllers and use it to fetch localized strings.

public class HomeController : ControllerBase
{
    private readonly IJsonStringLocalizer _localizer;

    public HomeController(IJsonStringLocalizer localizer)
    {
        _localizer = localizer;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var helloMessage = _localizer["Hello"];
        var welcomeMessage = _localizer["Welcome"];
        return Ok(new { Hello = helloMessage, Welcome = welcomeMessage });
    }
}

Step 4: Testing and Debugging

Run your application and test the endpoints to ensure they correctly respond with the appropriate localized content. Use tools like Postman or cURL, specifying the Accept-Language header to mimic requests from different locales.

Conclusion

Using JSON for localization in ASP.NET Core offers significant flexibility and ease of use compared to traditional methods. This approach aligns well with modern development practices, making it easier to manage and update localized content. By following the steps outlined above, you can effectively implement a robust and scalable localization system tailored to your needs.

Support ❤️
If you have enjoyed my content and code, do support me by buying a couple of coffees. This will enable me to dedicate more time to research and create new content. Cheers!
Share this Article
Share this article with your network to help others!
What's your Feedback?
Do let me know your thoughts around this article.