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.
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.
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).
These packages are included by default in ASP.NET Core, but confirm if you're using:
To localize strings, add a Resources folder and create .resx files such as:
Each resource file contains key-value pairs for translated text.
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);
});
}
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();
});
}
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();
}
}
public class SharedResource
{
}
Use IViewLocalizer to access translations in Razor views:
@inject IViewLocalizer Localizer
<h2>@Localizer["Welcome"]</h2>
To allow users to change the language manually (e.g., via dropdown):
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);
}
}
<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>
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.
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.
Satellite assemblies are compiled resources for specific cultures. They can be used for non-web .NET applications or when deploying localized content separately.
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.
Copyrights © 2024 letsupdateskills All rights reserved