ASP.NET Core Globalization and Localization Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      11 mins read      Difficulty-Level: beginner

Understanding ASP.NET Core Globalization and Localization

Introduction

Globalization and localization are crucial for creating web applications that cater to a diverse audience. In the context of ASP.NET Core, these concepts are pivotal for building applications that can support multiple languages and cultures, making your web apps more accessible and user-friendly.

Globalization refers to the process of designing and developing applications that are culturally adaptable. This includes the capability of the application to support different languages and cultures without code changes.

Localization involves the process of customizing the design and content of a globally designed application for a specific culture or locale. This includes translating text and other content into different languages, adjusting date and currency formats, and providing locale-specific features.

In ASP.NET Core, globalization and localization are managed using services that allow you to specify the culture and language preferences of the user. These services facilitate the automatic switching of cultural settings and language based on user preferences or other factors.

1. Setting Up the ASP.NET Core Project

To illustrate how localization and globalization work in ASP.NET Core, let's start by creating a simple ASP.NET Core MVC project. Follow these steps to set up the project:

  • Open Visual Studio and create a new ASP.NET Core Web Application.
  • Choose the MVC project template.
  • Configure the project with the desired .NET Core version and target framework.
  • Name your project and choose your preferred location to save it.
  • Once the project is created, open it in Visual Studio.

2. Configuring Localization Services

Now that we have our project set up, it's time to configure the localization services. This involves adding necessary services to the Startup.cs file.

The Startup.cs file in an ASP.NET Core project is where you configure application services and HTTP pipeline. To enable localization, you need to add the necessary services in the ConfigureServices method.

Here's how you can set up the services:

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

    services.AddMvc()
        .AddViewLocalization()
        .AddDataAnnotationsLocalization();
}

In this code snippet:

  • services.AddLocalization() configures localization services. The ResourcesPath option specifies the directory where the localization resources are stored. By default, resources are stored in the Resources folder.
  • services.AddMvc().AddViewLocalization() configures view localization services. This is required if you're localizing views.
  • services.AddMvc().AddDataAnnotationsLocalization() configures data annotation localization services. This is necessary if you’re localizing data annotations in models.

3. Creating Resource Files for Localization

Resource files are used to store text content in different languages. Each resource file corresponds to a specific culture or language. Resource files are typically created in the Resources folder.

Let's create two resource files for demonstration:

  • SharedResource.en.resx: This file will contain English translations.
  • SharedResource.es.resx: This file will contain Spanish translations.

To add resource files:

  1. Create a Resources folder in the project.
  2. Right-click on the Resources folder and add two new Resource Files.
  3. Name the first one SharedResource.en.resx and the second one SharedResource.es.resx.
  4. Add key-value pairs to each file. For example:

SharedResource.en.resx: | Key | Value | |--------|---------| | WelcomeMessage | Welcome to our website | | Title | Home Page |

SharedResource.es.resx: | Key | Value | |--------|----------| | WelcomeMessage | Bienvenido a nuestro sitio web | | Title | Página de inicio |

4. Configuring Middleware for Setting Culture

The middleware is responsible for determining the culture for the request and setting the appropriate culture information. This is typically done using the RequestLocalizationMiddleware.

You need to configure the middleware in the Configure method of the Startup.cs file:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

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

    var localizationOptions = new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en-US"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
    };

    app.UseRequestLocalization(localizationOptions);

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this configuration:

  • supportedCultures array defines which cultures are supported by the application.
  • RequestLocalizationOptions specifies the default request culture, the supported cultures, and the supported UI cultures.
  • UseRequestLocalization middleware is added to the application pipeline using the localizationOptions object.

5. Localizing Views

To localize views, you can use the IStringLocalizer interface or the IViewLocalizer interface. The IViewLocalizer interface provides a simplified way to localize views.

Here’s an example of how to use IViewLocalizer in a Razor view:

@model YourNamespace.Models.YourModel
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

@{
    ViewData["Title"] = Localizer["Title"];
}

<div class="text-center">
    <h1 class="display-4">@Localizer["WelcomeMessage"]</h1>
</div>

In this example:

  • @using Microsoft.AspNetCore.Mvc.Localization imports the necessary namespace.
  • @inject IViewLocalizer Localizer injects the IViewLocalizer service into the view.
  • Localizer["Title"] and Localizer["WelcomeMessage"] are used to fetch the localized strings from the resource files.

6. Localizing Models and Data Annotations

Localization of models and data annotations can be achieved using the IStringLocalizerFactory interface. This approach allows you to localize validation messages, labels, and other attributes in your models.

Here’s an example of how to use IStringLocalizerFactory in a model:

using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Localization;

namespace YourNamespace.Models
{
    public class YourModel
    {
        [Required(ErrorMessage = "The {0} field is required.")]
        [StringLength(100, ErrorMessage = "The {0} field must be a string with a maximum length of {1}.")]
        public string Name { get; set; }
    }
}

To localize the data annotations, you can use a custom attribute like this:

using System;
using Microsoft.Extensions.Localization;

namespace YourNamespace.Extensions
{
    public class LocalizedRequiredAttribute : RequiredAttribute
    {
        private readonly IStringLocalizer _localizer;

        public LocalizedRequiredAttribute(IStringLocalizerFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            var type = typeof(SharedResource);
            var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
            _localizer = factory.Create("SharedResource", assemblyName.Name);
        }

        public override string FormatErrorMessage(string name)
        {
            return _localizer[name];
        }
    }
}

In this example:

  • LocalizedRequiredAttribute is a custom attribute that inherits from the RequiredAttribute.
  • The IStringLocalizerFactory is injected to create a localizer for the SharedResource resource file.
  • FormatErrorMessage method is overridden to fetch the localized error message from the resource file.

To use the custom attribute, replace the Required attribute in your model with LocalizedRequiredAttribute:

using System.ComponentModel.DataAnnotations;
using YourNamespace.Extensions;

namespace YourNamespace.Models
{
    public class YourModel
    {
        [LocalizedRequired]
        [StringLength(100, ErrorMessage = "The {0} field must be a string with a maximum length of {1}.")]
        public string Name { get; set; }
    }
}

7. Testing Localization

Now that we've set up globalization and localization in our application, it's time to test it. You can change the culture for the request by appending a culture query string parameter or setting the language preference in the browser.

For example, to test the Spanish localization, access the URL with the culture parameter:

https://localhost:5001/Home?culture=es-ES

This should display the localized version of the application in Spanish.

You can also test the localization of validation messages by submitting a form with invalid data. The error messages should be displayed in the selected culture.

8. Advanced Localization Scenarios

In addition to basic localization, ASP.NET Core provides several advanced features that can be leveraged to enhance the localization support in your application.

Culture Providers

ASP.NET Core provides several culture providers that determine the current culture of a request. These providers are responsible for resolving the culture based on different sources such as the browser or the query string.

You can customize the culture providers by creating a custom implementation of the ICultureProvider interface.

Dynamic Resource Management

In some scenarios, you might need to manage resources dynamically, such as loading resources from a database or an external service.

You can create a custom implementation of the ResourceManagerStringLocalizer class to achieve this.

Custom Format Providers

The IStringLocalizer<T> and IViewLocalizer interfaces provide a flexible way to format localized strings. You can create custom format providers to customize the way localized strings are formatted.

Conclusion

Globalization and localization are essential for creating web applications that support multiple languages and cultures. In this article, we have explored how to configure globalization and localization in an ASP.NET Core MVC application. We have discussed how to set up the necessary services, create resource files, configure middleware, and test localization.

By following the steps outlined in this article, you can create a web application that is accessible to users from different parts of the world. With ASP.NET Core, you have the tools and flexibility to build highly localized applications that meet the needs of your users. Whether you're building a simple application or a large-scale web application, the principles of globalization and localization can help you create a more inclusive and user-friendly application.