Localization Implementation in ASP.NET Core: Enabling Global Audience Reach

Positiwise
4 min readAug 31, 2023

--

Building globally accessible websites and applications requires properly localizing the content to appeal to users from different cultures and regions. ASP.NET Core provides robust localization support to present content in the user’s preferred language and format.

In this comprehensive guide, we will explore various internationalization and localization features in ASP.NET Core, allowing you to easily adapt your web application for global audiences.

Introduction to Localization Concepts

Localization is the process of adapting a product or content to a specific locale or culture. This includes:

  • Translating text into the native language
  • Localizing elements like dates, currencies, etc., to match local conventions
  • Internationalizing code to enable localization

The key concepts:

  • Locale: Represents a specific culture, region, and language preferences. For example, en-US for English in the US.
  • Culture: Defines conventions like writing systems, calendars, number formatting, etc., for a geographic region. Can specify both culture name (en) and country (US).
  • Resources: Language-specific strings, images, etc. Content is separated from code.
  • Localizability: How easily an app can be adapted for other languages and cultures.

Localization makes applications more accessible for users around the world in their native cultural context.

Localization in ASP.NET Core

ASP.NET Core provides services and middleware for localizing content. The key components are:

  • Localization Middleware: Determines the request culture and provides string localization.
  • Data Annotations: Used for things like localizing model validation messages per culture.
  • View Localization: Displays localized strings, dates, numbers, etc., based on UI culture.
  • String Localization: Translated strings are loaded from resource files.
  • EF Core Support: Localize database content using globalization features.

These enable an end-to-end localization system for global ASP.NET Core web apps.

Configuring Cultures

The first step is registering which cultures your app will support by adding them to the ConfigureServices method:

var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR"),
new CultureInfo("es-MX")
};

services.Configure<RequestLocalizationOptions>(options =>
{
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});

This lists the cultures your app can localize to, like English US, French France, Spanish, Mexico etc.

Detecting Request Culture

The localization middleware needs to determine the culture for each request. This can be done via:

  • User Preferences: Browser language settings
  • UI Culture Parameter: uiCulture query string parameter
  • URL Path: Culture segment of route path like http://example.com/en-US
  • Cookie: Language preference saved in a cookie
  • Custom Logic: Any custom logic in middleware to set culture, e.g.: based on user preference from DB.

We configure this in RequestLocalizationOptions:

options.ApplyCurrentCultureToResponseHeaders = true; 
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new[]
{
new RouteDataRequestCultureProvider(),
new CookieRequestCultureProvider()
};

This provides flexible culture detection from various sources like routes, cookies etc.

Localizing Views

The view localization system uses the detected culture to render culture-specific strings, formats etc.

Localized Views

We can provide culture-specific versions of Razor views by suffixing the name like About.cshtml, About.fr.cshtml, About.es.cshtml etc. The middleware will automatically use the matching one for the request culture.

Localized Strings

Resource files contain string translations for each language. They are named resources.{culture}.resx like resources.en-US.resx. These are automatically read based on culture.

In Razor views, we inject the IStringLocalizer service to access translated strings:

@inject IStringLocalizer<HomePage> L 

<h1>@L["WelcomeMessage"]</h1>

The resource files provide the translated string for the culture.

Localized Content

Built-in helpers like DateTime.ToLocalizedString() format dates, numbers etc. as per culture conventions:

@DateTime.Now.ToLocalizedString()

@10.5.ToLocalizedString(culture: null)

This makes it easy to localize views without code changes.

Localizing Data Models

ASP.NET data annotations provide attributes for model validation error messages. These can be localized like:

[Display(Name = "DateOfBirth", ResourceType = typeof(Resources.HomePage))]
[Required(ErrorMessageResourceName = "RequiredDate",
ErrorMessageResourceType = typeof(Resources.HomePage))]
public DateTime DOB { get; set; }

The ResourceType points to the class containing culture-specific strings.

For client-side validation, the IStringLocalizer scripts generate localized messages for jQuery unobtrusive validation.

Localizing APIs

ASP.NET Core provides request localization for web APIs too. The Accept-Language header can be used to determine culture.

Resources can provide localized messages:

[HttpGet("about")]
public IActionResult About()
{
return Ok(SharedResource.AboutText);
}

EF Core can also be configured to localize database content based on requested culture.

Testing Localization

With the app configured for localization, important aspects of testing are:

  • Request culture resolvers detect expected culture for different requests
  • Views are rendering content properly for each supported culture
  • Dates, numbers, and currencies are formatted correctly per culture
  • Strings and messages extracted into resource files are displaying properly
  • Model validation messages are localized as per culture
  • Routes, cookies, and query params that switch culture work correctly

Automated testing helps verify localization works across the app.

Localization Best Practices

Some things to keep in mind for effective localization:

  • Support RTL languages with appropriate CSS and markup
  • Avoid concatenating translated strings. Use placeholders with parameters.
  • Use culture-neutral identifiers and names like datetime-local for elements
  • Plan layouts to accommodate variable string lengths in different languages
  • Enable content localization in databases using EF Core globals
  • Implement layered localization providers to customize culture sources
  • Follow recommended naming conventions for resource files
  • Leverage tools like locstudio to manage translations
  • Use CI/CD pipelines to automate building resource files for each culture

Conclusion

Localization is essential for global applications targeting worldwide users. ASP.NET Core provides comprehensive cultural conventions and an extensive framework for localizing. Key concepts covered include detecting culture via routes, cookies, etc., rendering localized views and strings, and localizing model validation. Built-in helpers format dates, numbers, and currencies. Planning for localization from the start and using best practices results in global-ready applications. ASP.NET Core has the tooling to make your app accessible no matter the language, region, or culture.

--

--

Positiwise
Positiwise

Written by Positiwise

Positiwise.com is a leading IT company, based in India, offering top-notch full-cycle software development through its dedicated team of professionals.

No responses yet