ASP.NET core localization

This article shows how to work with localized strings in your app by following these steps:

1. Create a resources folder and add a resource file per language:
 

2. Create a dummy class with that name under project default namespace:


3. In Startup.cs add the localization services:

services.AddLocalization(o => o.ResourcesPath = "Resources");
	

and for model binding error message localization:

services.AddControllers()
.AddDataAnnotationsLocalization(o =>
{
	o.DataAnnotationLocalizerProvider = (type, factory) =>
	{
		return factory.Create(typeof(StringResource));
	};
});

configure to set the culture based on the request:
var supportedCultures = new[]
{
	new CultureInfo("en-US"),
	new CultureInfo("he-IL"),
};
		

services.Configure<RequestLocalizationOptions>(options =>
{
	options.DefaultRequestCulture = new RequestCulture("he-IL");
	options.SupportedCultures = supportedCultures;
	options.SupportedUICultures = supportedCultures;
	options.RequestCultureProviders = new List<IRequestCultureProvider> 
	{
		new QueryStringRequestCultureProvider(),
		new CookieRequestCultureProvider(),
		new AcceptLanguageHeaderRequestCultureProvider()
	};
});
4. Add middleware:
app.UseRequestLocalization();
before everything else.

5. Inject into controllers:
IStringLocalizer<StringResource> sharedLocalizer

6. Then use it like this: sharedLocalizer["MY_STRING"]
Or for model validation [Required(ErrorMessage="MY_STRING")]

Post a Comment

Previous Post Next Post