.NET - Globalization and Localization

.NET - Globalization and Localization

Globalization and Localization in .NET

Globalization and Localization in .NET are powerful features that allow developers to create applications that support multiple cultures, languages, date formats, currencies, and UI strings. This guide will help you understand how to build multilingual and culture-aware applications using ASP.NET Core.

What is Globalization in .NET?

Globalization is the process of designing and developing applications that can function in multiple cultures. It prepares the application to handle data formats, number formats, date/time formats, and languages according to the user's locale settings.

What is Localization in .NET?

Localization is the process of adapting the application to a specific culture or language by translating the UI elements like labels, error messages, buttons, etc. It typically involves the use of resource files (.resx).

Key Concepts of Globalization and Localization

  • Culture: Represents the language and region (e.g., en-US, fr-FR).
  • UICulture: Determines which resource files to load.
  • ResourceManager: Loads localized strings at runtime.
  • IStringLocalizer & IViewLocalizer: Interfaces used for retrieving localized strings in ASP.NET Core.
  • Middleware: Helps apply culture settings on each request.

Setting Up Globalization and Localization in ASP.NET Core

Step 1: Install Required Packages

These packages are included by default in ASP.NET Core, but confirm if you're using:

  • Microsoft.Extensions.Localization
  • Microsoft.AspNetCore.Localization

Step 2: Create Resource Files (.resx)

To localize strings, add a Resources folder and create .resx files such as:

  • Resources/SharedResource.resx (default)
  • Resources/SharedResource.fr.resx (French)
  • Resources/SharedResource.de.resx (German)

Each resource file contains key-value pairs for translated text.

Step 3: Configure Services in Startup.cs

Add localization services to your application:


public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddControllersWithViews()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[] { "en", "fr", "de" };
        options.SetDefaultCulture("en")
               .AddSupportedCultures(supportedCultures)
               .AddSupportedUICultures(supportedCultures);
    });
}

Step 4: Configure Middleware


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var localizationOptions = app.ApplicationServices
        .GetService<IOptions<RequestLocalizationOptions>>().Value;

    app.UseRequestLocalization(localizationOptions);

    app.UseStaticFiles();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

Accessing Localized Strings Using IStringLocalizer


public class HomeController : Controller
{
    private readonly IStringLocalizer<SharedResource> _localizer;

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

    public IActionResult Index()
    {
        ViewBag.Message = _localizer["Welcome"];
        return View();
    }
}

SharedResource.cs (marker class)


public class SharedResource
{
}

Accessing Localized Strings in Views

Use IViewLocalizer to access translations in Razor views:


@inject IViewLocalizer Localizer

<h2>@Localizer["Welcome"]</h2>

Changing Culture Dynamically

To allow users to change the language manually (e.g., via dropdown):

Create a CultureController


public class CultureController : Controller
{
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(
                new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });

        return LocalRedirect(returnUrl);
    }
}

Create a Language Switch View


<form asp-controller="Culture" asp-action="SetLanguage" method="post">
    <select name="culture" onchange="this.form.submit();">
        <option value="en">English</option>
        <option value="fr">FranΓ§ais</option>
        <option value="de">Deutsch</option>
    </select>
    <input type="hidden" name="returnUrl" value="@Context.Request.Path" />
</form>

Localizing Data Annotations

Localization also applies to validation messages:


public class ContactModel
{
    [Required(ErrorMessage = "NameRequired")]
    [Display(Name = "FullName")]
    public string Name { get; set; }
}

These keys (NameRequired, FullName) should be added in the appropriate resource files.

Using JSON Resource Files (Optional)

You can use custom JSON-based localization by implementing your own localization provider, but it's more advanced and not recommended for most standard projects.

Using Satellite Assemblies for Localization

Satellite assemblies are compiled resources for specific cultures. They can be used for non-web .NET applications or when deploying localized content separately.

Best Practices

  • Keep resource keys consistent and meaningful.
  • Use marker classes to scope localization to specific views or controllers.
  • Avoid hardcoding strings in your code.
  • Test different cultures using browser settings or cookies.
  • Structure resource files for modular reusability (e.g., per feature or module).

Common Errors in Localization

  • Missing resource key results in fallback to default culture.
  • Not registering localization middleware can cause untranslated views.
  • Typos in resource file names (must match namespace structure).

Globalization and Localization in .NET allow developers to create applications that are inclusive, culturally aware, and user-friendly across languages. By using resource files, middleware, and culture-specific settings, you can develop robust multilingual ASP.NET Core web applications.

Now that you understand the basics and implementation details, you can confidently develop applications for a global audience using ASP.NET Core’s built-in localization system.

Beginner 5 Hours
.NET - Globalization and Localization

Globalization and Localization in .NET

Globalization and Localization in .NET are powerful features that allow developers to create applications that support multiple cultures, languages, date formats, currencies, and UI strings. This guide will help you understand how to build multilingual and culture-aware applications using ASP.NET Core.

What is Globalization in .NET?

Globalization is the process of designing and developing applications that can function in multiple cultures. It prepares the application to handle data formats, number formats, date/time formats, and languages according to the user's locale settings.

What is Localization in .NET?

Localization is the process of adapting the application to a specific culture or language by translating the UI elements like labels, error messages, buttons, etc. It typically involves the use of resource files (.resx).

Key Concepts of Globalization and Localization

  • Culture: Represents the language and region (e.g., en-US, fr-FR).
  • UICulture: Determines which resource files to load.
  • ResourceManager: Loads localized strings at runtime.
  • IStringLocalizer & IViewLocalizer: Interfaces used for retrieving localized strings in ASP.NET Core.
  • Middleware: Helps apply culture settings on each request.

Setting Up Globalization and Localization in ASP.NET Core

Step 1: Install Required Packages

These packages are included by default in ASP.NET Core, but confirm if you're using:

  • Microsoft.Extensions.Localization
  • Microsoft.AspNetCore.Localization

Step 2: Create Resource Files (.resx)

To localize strings, add a Resources folder and create .resx files such as:

  • Resources/SharedResource.resx (default)
  • Resources/SharedResource.fr.resx (French)
  • Resources/SharedResource.de.resx (German)

Each resource file contains key-value pairs for translated text.

Step 3: Configure Services in Startup.cs

Add localization services to your application:

public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddControllersWithViews() .AddViewLocalization() .AddDataAnnotationsLocalization(); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { "en", "fr", "de" }; options.SetDefaultCulture("en") .AddSupportedCultures(supportedCultures) .AddSupportedUICultures(supportedCultures); }); }

Step 4: Configure Middleware

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var localizationOptions = app.ApplicationServices .GetService<IOptions<RequestLocalizationOptions>>().Value; app.UseRequestLocalization(localizationOptions); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }

Accessing Localized Strings Using IStringLocalizer

public class HomeController : Controller { private readonly IStringLocalizer<SharedResource> _localizer; public HomeController(IStringLocalizer<SharedResource> localizer) { _localizer = localizer; } public IActionResult Index() { ViewBag.Message = _localizer["Welcome"]; return View(); } }

SharedResource.cs (marker class)

public class SharedResource { }

Accessing Localized Strings in Views

Use IViewLocalizer to access translations in Razor views:

@inject IViewLocalizer Localizer <h2>@Localizer["Welcome"]</h2>

Changing Culture Dynamically

To allow users to change the language manually (e.g., via dropdown):

Create a CultureController

public class CultureController : Controller { public IActionResult SetLanguage(string culture, string returnUrl) { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue( new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }); return LocalRedirect(returnUrl); } }

Create a Language Switch View

<form asp-controller="Culture" asp-action="SetLanguage" method="post"> <select name="culture" onchange="this.form.submit();"> <option value="en">English</option> <option value="fr">Français</option> <option value="de">Deutsch</option> </select> <input type="hidden" name="returnUrl" value="@Context.Request.Path" /> </form>

Localizing Data Annotations

Localization also applies to validation messages:

public class ContactModel { [Required(ErrorMessage = "NameRequired")] [Display(Name = "FullName")] public string Name { get; set; } }

These keys (NameRequired, FullName) should be added in the appropriate resource files.

Using JSON Resource Files (Optional)

You can use custom JSON-based localization by implementing your own localization provider, but it's more advanced and not recommended for most standard projects.

Using Satellite Assemblies for Localization

Satellite assemblies are compiled resources for specific cultures. They can be used for non-web .NET applications or when deploying localized content separately.

Best Practices

  • Keep resource keys consistent and meaningful.
  • Use marker classes to scope localization to specific views or controllers.
  • Avoid hardcoding strings in your code.
  • Test different cultures using browser settings or cookies.
  • Structure resource files for modular reusability (e.g., per feature or module).

Common Errors in Localization

  • Missing resource key results in fallback to default culture.
  • Not registering localization middleware can cause untranslated views.
  • Typos in resource file names (must match namespace structure).

Globalization and Localization in .NET allow developers to create applications that are inclusive, culturally aware, and user-friendly across languages. By using resource files, middleware, and culture-specific settings, you can develop robust multilingual ASP.NET Core web applications.

Now that you understand the basics and implementation details, you can confidently develop applications for a global audience using ASP.NET Core’s built-in localization system.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved