ASP.NET Core 8 Web API -

Localization

Localization is the process of adapting your application to support multiple languages and cultures. ASP.NET Core provides built-in support for localization, making it easy to create web APIs that can serve content in different languages based on user preferences. This guide covers how to implement localization in an ASP.NET Core 8 Web API, along with best practices and detailed explanations.


1. Introduction to Localization

Localization involves translating the user interface and content of your application into different languages. This process includes handling different cultural norms, such as date formats, number formats, and text direction.


2. Setting Up Localization in ASP.NET Core

To set up localization in an ASP.NET Core application, you need to configure localization services and add resource files for different languages.

2.1 Configure Services Program.cs:
        
            var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

var app = builder.Build();

var supportedCultures = new[] { "en-US", "fr-FR", "es-ES" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    


2.2 Add Resource Files

Resource files store the localized text for different languages. Create resource files for each language you want to support in the Resources folder.

Example:
        
            // Create the following resource files in the Resources folder:
// Resources/Controllers.HomeController.en-US.resx
// Resources/Controllers.HomeController.fr-FR.resx
// Resources/Controllers.HomeController.es-ES.resx

// Example content for Resources/Controllers.HomeController.en-US.resx:
<root>
  <data name="Welcome" xml:space="preserve">
    <value>Welcome</value>
  </data>
</root>

// Example content for Resources/Controllers.HomeController.fr-FR.resx:
<root>
  <data name="Welcome" xml:space="preserve">
    <value>Bienvenue</value>
  </data>
</root>

// Example content for Resources/Controllers.HomeController.es-ES.resx:
<root>
  <data name="Welcome" xml:space="preserve">
    <value>Bienvenido</value>
  </data>
</root>
        
    

3. Using Localization in Controllers

Inject the IStringLocalizer service into your controllers to access localized strings.

3.1 Injecting IStringLocalizer Example:
        
            [ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

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

4. Handling Request Localization

ASP.NET Core can automatically determine the culture and UI culture for each request based on the request's headers or query string parameters.

4.1 Configure Request Localization Middleware Program.cs:
        
            var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

var app = builder.Build();

var supportedCultures = new[] { "en-US", "fr-FR", "es-ES" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    

5. Advanced Localization Scenarios

Advanced localization scenarios include using data annotations for localized validation messages, custom localizers, and dynamic resource files.

5.1 Localized Validation Messages Example:
        
            // Add the following resource files for validation messages:
// Resources/ValidationMessages.en-US.resx
// Resources/ValidationMessages.fr-FR.resx
// Resources/ValidationMessages.es-ES.resx

// Example content for Resources/ValidationMessages.en-US.resx:
<root>
  <data name="Required" xml:space="preserve">
    <value>The {0} field is required.</value>
  </data>
</root>

// Example content for Resources/ValidationMessages.fr-FR.resx:
<root>
  <data name="Required" xml:space="preserve">
    <value>Le champ {0} est requis.</value>
  </data>
</root>

// Example content for Resources/ValidationMessages.es-ES.resx:
<root>
  <data name="Required" xml:space="preserve">
    <value>El campo {0} es obligatorio.</value>
  </data>
</root>

// Use localized validation messages in your models:
public class Product
{
    [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.ValidationMessages))]
    public string Name { get; set; }
}
        
    


5.2 Custom Localizers Example:
        
            // Create a custom localizer to extend the default localization functionality:
public class CustomStringLocalizer : IStringLocalizer
{
    private readonly IStringLocalizer _localizer;

    public CustomStringLocalizer(IStringLocalizerFactory factory)
    {
        _localizer = factory.Create(typeof(CustomStringLocalizer));
    }

    public LocalizedString this[string name] => _localizer[name];

    public LocalizedString this[string name, params object[] arguments] => _localizer[name, arguments];

    public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures) => _localizer.GetAllStrings(includeParentCultures);

    public IStringLocalizer WithCulture(CultureInfo culture) => _localizer.WithCulture(culture);
}

// Register the custom localizer in Program.cs:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddSingleton<IStringLocalizer, CustomStringLocalizer>();

var app = builder.Build();

var supportedCultures = new[] { "en-US", "fr-FR", "es-ES" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    

6. Best Practices for Localization


7. Conclusion

Localization is an important feature for global applications. By implementing localization in your ASP.NET Core 8 Web API, you can provide a better user experience for users from different linguistic and cultural backgrounds. Follow best practices to ensure your localization strategy is effective and maintainable.