Implementing a multi-language (localized) .NET Core application involves leveraging the localization features provided by the framework to support multiple cultures and languages. Below is a step-by-step guide to help you implement localization in your .NET Core application, along with best practices to ensure a clean and maintainable implementation.
Step-by-Step Guide to Implement Multi-Language Support in .NET Core
Prerequisites
- .NET Core SDK installed on your development machine.
- Visual Studio or Visual Studio Code as your development environment.
- Basic knowledge of ASP.NET Core MVC or Razor Pages (depending on your application type).
Step 1: Create a New ASP.NET Core Web Application
If you already have an application, you can skip this step.
- Open Visual Studio.
- Click on Create a new project.
- Select ASP.NET Core Web App (Model-View-Controller) or ASP.NET Core Web App for Razor Pages.
- Name your project and click Create.
- Choose the .NET 7.0 framework (or the latest available).
- Click Create.
Step 2: Add Localization Services
-
Open the Startup.cs file (for .NET Core 3.x) or Program.cs (for .NET 6 and later, as the Startup.cs is consolidated).
-
In the ConfigureServices method, add localization services:
services.AddLocalization(options => options.ResourcesPath = "Resources");
-
Configure supported cultures and localization options:
var supportedCultures = new[] { "en-US", "fr-FR", "es-ES" };
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures.Select(c => new CultureInfo(c)).ToList();
options.SupportedUICultures = supportedCultures.Select(c => new CultureInfo(c)).ToList();
// Optionally, set up culture providers here
});
Step 3: Configure the Request Localization Middleware
In the Configure method (in Startup.cs or Program.cs), add the following before the UseEndpoints method:
var supportedCultures = new[] { "en-US", "fr-FR", "es-ES" };
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture("en-US")
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
Step 4: Create Resource Files
-
Create a folder named Resources at the root of your project (as specified in ResourcesPath).
-
For shared resources:
-
For view-specific resources (e.g., for HomeController):
-
For data annotations:
- Create resource files similar to above in a
Resources folder.
Step 5: Inject Localization into Controllers and Views
For Controllers:
-
Inject IStringLocalizer or IStringLocalizer<T> into your controller:
public class HomeController : Controller
{
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
public IActionResult Index()
{
ViewData["Message"] = _localizer["WelcomeMessage"];
return View();
}
}
For Views (Razor Pages):
-
Inject IViewLocalizer or IStringLocalizer at the top of your view:
@inject IViewLocalizer Localizer
-
Use localized strings in your view:
<h1>@Localizer["WelcomeMessage"]</h1>
Step 6: Use Localized Strings in Your Application
-
Open your default resource file (e.g., SharedResource.resx) and add key-value pairs:
| Name | Value |
|---|
| WelcomeMessage | Welcome to our application! |
| AboutUs | Learn more about us here. |
-
Open the culture-specific resource files (e.g., SharedResource.fr-FR.resx) and provide translations:
| Name | Value |
|---|
| WelcomeMessage | Bienvenue dans notre application ! |
| AboutUs | En savoir plus sur nous ici. |
Step 7: Configure Culture Providers (Optional)
You can configure how the application determines the culture for each request.
By default, the RequestLocalizationOptions will use the Accept-Language header. You can add more providers, such as query string or cookie providers.
Example to add a query string provider:
options.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider());
This allows users to specify the culture via a query string parameter, like ?culture=fr-FR.
Step 8: Test Localization
-
Run your application.
-
Test the default culture (en-US) by navigating to your page and ensure the default language is displayed.
-
Switch the culture by:
- Changing the
Accept-Language header in your browser settings.
- Using the culture query string if you have set up the
QueryStringRequestCultureProvider.
Example: https://localhost:5001/?culture=fr-FR
-
Verify that the application displays the content in the selected language.
Best Practices for Multi-Language .NET Core Applications
-
Consistent Resource Keys:
- Use consistent and descriptive keys in your resource files.
- Prefer using the default text as the key to reduce duplication and errors.
-
Organize Resource Files:
- Keep resource files organized, especially in larger applications.
- Group resources by feature or controller when appropriate.
-
Avoid Hardcoding Strings:
- Do not hardcode any user-facing strings in your views or controllers.
- Always use the localizer to ensure all content is localizable.
-
Fallback Culture:
- Ensure you have a fallback culture (usually the default culture) to handle cases where a translation is missing.
-
Use Pluralization and Gender:
- For languages that have pluralization rules or gender-specific translations, use the
IStringLocalizer's support for string formatting.
-
Localize Data Annotations:
-
Use localization in validation messages and data annotations:
[Required(ErrorMessage = "FieldRequired")]
public string Name { get; set; }
-
Add the resource keys in your resource files.
-
Testing Localization:
- Regularly test your application in all supported cultures.
- Use automated tests to verify that localization is working as expected.
-
Use Localization Tools:
- Consider using tools like ResX Resource Manager to manage resource files efficiently.
-
Performance Considerations:
- Be mindful of the performance impact of loading large resource files.
- Load only the necessary resources when possible.
-
Regularly Update Translations:
- Keep your translations up to date with any changes in your application.
- Consider using professional translators for accurate translations.
-
Handle Right-to-Left (RTL) Languages:
- If supporting RTL languages (like Arabic or Hebrew), ensure your UI layout supports RTL by adding the attribute when needed.
Conclusion
Implementing multi-language support in a .NET Core application involves setting up localization services, creating resource files for different cultures, and using localizers in your code to provide the translations. Following best practices such as organized resource management, consistent key usage, and thorough testing will ensure your application is scalable, maintainable, and provides a good user experience across different languages.
References:
Feel free to reach out if you have any specific questions or need further clarification on any of the steps!