Introduction
Implementing localization and globalization in an ASP.NET Core Web API involves configuring the application to support multiple languages and cultures and then using resource files to provide translated content. Here, I'll provide a step-by-step example of how to achieve this. In this example, we'll create a simple Web API that supports English and Spanish languages.
Create a new ASP.NET Core Web API Project
Start by creating a new ASP.NET Core Web API project using Visual Studio or the .NET CLI. You can use the following command to create a new API project.
dotnet new webapi -n LocalizationInAspNetCore
Configure Supported Cultures
Open the Startup.cs file and configure the supported cultures and localization services in the ConfigureServices method. In this example, we'll support English (en-US) and Spanish (es-ES).
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Options;
Author: Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
}
Create Resource Files
Create resource files for each supported language under a folder named "Resources" in your project. For example, create Resources/Messages.en-US.resx and Resources/Messages.es-ES.resx. Add keys and values for the localized strings you want to use.
Messages.en-US.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="greeting" xml:space="preserve">
<value>Hello, Sardar Mudassar Ali Khan!</value>
</data>
</root>
Messages.es-ES.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="greeting" xml:space="preserve">
<value>Hola, Mundo!</value>
</data>
</root>
Configure Middleware for Localization
In the Configure method of Startup.cs, add middleware for localization.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Localization;
Author: Sardar Mudassar Ali Khan
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ app.UseRequestLocalization(app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);
}
Create a Controller
Create a simple controller to demonstrate localization. For example, create a GreetingController.cs.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class GreetingController : ControllerBase
{
private readonly IStringLocalizer<GreetingController> _localizer;
public GreetingController(IStringLocalizer<GreetingController> localizer)
{
_localizer = localizer;
}
[HttpGet]
public IActionResult Get()
{
var greeting = _localizer["greeting"];
return Ok(greeting);
}
}
Run the Application and Test the Endpoints
Run the application and access the API endpoint. You can specify the desired language in the request header, for example.
- For English: Accept-Language: en-US
- For Spanish: Accept-Language: es-ES
The response will be localized based on the specified language.
In conclusion, implementing localization and globalization in an ASP.NET Core Web API is essential when building applications for a global audience. By following the steps outlined in the example above, you can ensure that your application supports multiple languages and cultures, providing a better user experience and broader accessibility. Here are the key takeaways:
- Configuration: Configure the supported cultures and localization services in the Startup.cs file. Define the cultures you want to support and set the default culture.
- Resource Files: Create resource files for each supported language. These files contain key-value pairs for localized content such as strings, messages, and labels.
- Middleware: Add middleware for localization in the Configure method of Startup.cs to enable language detection and resource loading based on user preferences.
- Controller: In your controllers, inject the IStringLocalizer service to retrieve localized content and use it in your API responses.
- Testing: Test your API by specifying the desired language in the request header to ensure that the responses are localized according to the user's preference.
By implementing localization and globalization techniques, you can make your ASP.NET Core Web API more accessible to users from different linguistic and cultural backgrounds, enhancing the user experience and potentially expanding your application's reach to a broader audience.