ASP.Net Core localization

Tedd Hansen picture Tedd Hansen · Aug 30, 2016 · Viewed 17k times · Source

ASP.Net core features new support for localization.

In my project I need only one language. For most of the text and annotations I can specify things in my language, but for text coming from ASP.Net Core itself the language is English.

Examples:

  • Passwords must have at least one uppercase ('A'-'Z').
  • Passwords must have at least one digit ('0'-'9').
  • User name '[email protected]' is already taken.
  • The E-post field is not a valid e-mail address.
  • The value '' is invalid.

I've tried setting the culture manually, but the language is still English.

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("nb-NO"),
    SupportedCultures = new List<CultureInfo> { new CultureInfo("nb-NO") },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo("nb-NO") }
});

How can I change the language of ASP.Net Core, or override its default text?

Answer

Ralf B&#246;nning picture Ralf Bönning · Aug 30, 2016

The listed error messages are defined in ASP.NET Core Identity and provided by the IdentityErrorDescriber. I did not found translated resource files so far and I think they are not localized. On my system (German locale) they are not translated as well although the CultureInfo is set correctly.

You can configure a custom IdentityErrorDescriber to return your own messages as well as their translations. It is described e.g. in How to change default error messages of MVC Core ValidationSummary?

In the Configure method of the Startup.cs you can wire up your Error Describer class inherited from IdentityErrorDescriber like

 services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddErrorDescriber<TranslatedIdentityErrorDescriber>();

For other default model error messages (like invalid number) you can provide own accessor functions in the ModelBindingMessageProvider. This provider is used by ASP.NET Core MVC and can be configured in the Startup.cs as well.

services.AddMvc(
            options => 
            options.ModelBindingMessageProvider.ValueIsInvalidAccessor = s => $"My not valid text for {s}");