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:
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?
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}");
Let me have a comprehensive response for this question and describe how I came up with a solution after reading .net core source code.
before any further description, first install this package using NuGet Microsoft.Extensions.Localization
as you guys might remember in asp.net full framework, switching between cultures was pretty straightforward
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
but in .net core, the culture is not tied to the current thread anymore. The asp.net core engine has a pipeline and we can add different MiddleWares to this pipeline, so the RequestLocalizationMiddleware is the middleware class for handling localization, we might have multiple providers so it will iterate through all the culture providers like QueryStringRequestCultureProvider, CookieRequestCultureProvider, AcceptLanguageHeaderRequestCultureProvider, …
as soon as the request localization middleware can get the current locale from the first provider then it will ignore others and pass the request to the next middleware in the pipeline, so the order of providers in the list really matters.
i personally prefer to store the culture in the browser cookie, so since the CookieRequestCultureProvider is not the first culture provider in the list i move it to the top of the list, the configuration of this part in Startup.cs > ConfigureServices is as below
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fa-IR"),
new CultureInfo("de-DE")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
var defaultCookieRequestProvider =
options.RequestCultureProviders.FirstOrDefault(rcp =>
rcp.GetType() == typeof(CookieRequestCultureProvider));
if (defaultCookieRequestProvider != null)
options.RequestCultureProviders.Remove(defaultCookieRequestProvider);
options.RequestCultureProviders.Insert(0,
new CookieRequestCultureProvider()
{
CookieName = ".AspNetCore.Culture",
Options = options
});
});
let me describe the above code, our app default culture is en-US and we only support English, Farsi, Germany so if the browser has different locale or you setting language is other than these 3 languages then the app must switch to default culture. in above code i just remove CookieCultureProvider from the list and add it as the first provider in the list (* I already described the reason why it must be the first one*). The default CookieName is working for me, you can change it if you want.
don't forget to add the below code beneath of Configure(IApplicationBuilder app, IHostingEnvironment env) in Startup.cs
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
so far so good. To have resource files you must specify the path for the resources, I separately specify the resource for Controller, Views, ViewModels and SharedResources in web project root path, the hierarchy is like below
|-Resoures
|---Controllers
|---Views
|---Models
|---SharedResource.resx
|---SharedResource.fa-IR.resx
|---SharedResource.de-DE.resx
keep in mind that for the SharedResource create an empty class with the same name in the Web Project root path i mean a SharedResource.cs with a class with the same name inside.
Add the following code snippet inside the Startup.cs for specifying the resource path and the rest.
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources/Views"; }) // this line is not required, it is just for more clarification
.AddDataAnnotationsLocalization();
with this configurations for example when you inject IStringLocalizer inside the controller you have to have corresponding resource files in Resources > Controllers folder (which are HomeController.resx, HomeController.fa-IR.resx, HomeController.de-DE.resx) we can also separate the path by .(say dot) in file name i mean Resources/Controllers/HomeController.resx can be a file in Resources/Controllers.HomeController.resx, you have to inject IViewLocalizer into views to have the localization inside views correspondingly you have to have resources files for Views inside Resources/Views folder, for the ViewModels since we named the folder Models please put all ViewModels inside a pre-created Folder in the Web project root path with the name Models, if the folder has another name or you prefer another name don't forget to rename the Models folder under Resource folder. then you need to do nothing but annotating models, for example, annotate ViewModel properties with [DisplayName("User Emailaddress")] then create resources in the corresponding resource files inside the model (the name of the files must match the model class name) with the same key ("User Emailaddress").
let's finish with where we already started, I mean CookieRequestCultureProvider. as I said earlier I prefer to store it in a cookie, but it is a bit tricky, because cookie parsing is a bit different from what you might expected, just add below code where you want to change the culture, only replace preferedCulture with your culture preference
var preferedCulture = "fa-IR"; // get the culture from user, i just mock it here in a variable
if (HttpContext.Response.Cookies.ContainsKey(".AspNetCore.Culture"))
{
HttpContext.Response.Cookies.Delete(".AspNetCore.Culture");
}
HttpContext.Response.Cookies.Append(".AspNetCore.Culture",
$"c={preferedCulture}|uic={preferedCulture}", new CookieOptions {Expires = DateTime.UtcNow.AddYears(1)});
here we go, our sp.net core web app is now localized :)
Based on rboe's and Tedd Hansen's excellent answers, I have written an IStringLocalizer
based IdentityErrorDescriber
for my own use, thought I'd share it here in case anyone needs multiple language support :)
The basic idea is to create a resource file for your default language and any other languages in the usual way. (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization)
Located at (If you keep my class name):
/Resources/yournamespace.LocalizedIdentityErrorDescriber.resx
/Resources/yournamespace.LocalizedIdentityErrorDescriber.fr.resx
etc...
Within these you will use the error codes (ex: DefaultError, ConcurrencyError) as the key.
Then add the class below
LocalizedIdentityErrorDescriber.cs
public class LocalizedIdentityErrorDescriber : IdentityErrorDescriber
{
/// <summary>
/// The <see cref="IStringLocalizer{LocalizedIdentityErrorDescriber}"/>
/// used to localize the strings
/// </summary>
private readonly IStringLocalizer<LocalizedIdentityErrorDescriber> localizer;
/// <summary>
/// Initializes a new instance of the <see cref="LocalizedIdentityErrorDescriber"/> class.
/// </summary>
/// <param name="localizer">
/// The <see cref="IStringLocalizer{LocalizedIdentityErrorDescriber}"/>
/// that we will use to localize the strings
/// </param>
public LocalizedIdentityErrorDescriber(IStringLocalizer<LocalizedIdentityErrorDescriber> localizer)
{
this.localizer = localizer;
}
/// <summary>
/// Returns the default <see cref="IdentityError" />.
/// </summary>
/// <returns>The default <see cref="IdentityError" /></returns>
public override IdentityError DefaultError()
{
return this.GetErrorByCode("DefaultError");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a concurrency failure.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a concurrency failure.</returns>
public override IdentityError ConcurrencyFailure()
{
return this.GetErrorByCode("ConcurrencyFailure");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password mismatch.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a password mismatch.</returns>
public override IdentityError PasswordMismatch()
{
return this.GetErrorByCode("PasswordMismatch");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating an invalid token.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating an invalid token.</returns>
public override IdentityError InvalidToken()
{
return this.GetErrorByCode("InvalidToken");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating an external login is already associated with an account.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating an external login is already associated with an account.</returns>
public override IdentityError LoginAlreadyAssociated()
{
return this.GetErrorByCode("LoginAlreadyAssociated");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified user <paramref name="userName" /> is invalid.
/// </summary>
/// <param name="userName">The user name that is invalid.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specified user <paramref name="userName" /> is invalid.</returns>
public override IdentityError InvalidUserName(string userName)
{
return this.FormatErrorByCode("InvalidUserName", (object)userName);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified <paramref name="email" /> is invalid.
/// </summary>
/// <param name="email">The email that is invalid.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specified <paramref name="email" /> is invalid.</returns>
public override IdentityError InvalidEmail(string email)
{
return this.FormatErrorByCode("InvalidEmail", (object)email);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified <paramref name="userName" /> already exists.
/// </summary>
/// <param name="userName">The user name that already exists.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specified <paramref name="userName" /> already exists.</returns>
public override IdentityError DuplicateUserName(string userName)
{
return this.FormatErrorByCode("DuplicateUserName", (object)userName);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified <paramref name="email" /> is already associated with an account.
/// </summary>
/// <param name="email">The email that is already associated with an account.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specified <paramref name="email" /> is already associated with an account.</returns>
public override IdentityError DuplicateEmail(string email)
{
return this.FormatErrorByCode("DuplicateEmail", (object)email);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified <paramref name="role" /> name is invalid.
/// </summary>
/// <param name="role">The invalid role.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specific role <paramref name="role" /> name is invalid.</returns>
public override IdentityError InvalidRoleName(string role)
{
return this.FormatErrorByCode("InvalidRoleName", (object)role);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating the specified <paramref name="role" /> name already exists.
/// </summary>
/// <param name="role">The duplicate role.</param>
/// <returns>An <see cref="IdentityError" /> indicating the specific role <paramref name="role" /> name already exists.</returns>
public override IdentityError DuplicateRoleName(string role)
{
return this.FormatErrorByCode("DuplicateRoleName", (object)role);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a user already has a password.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a user already has a password.</returns>
public override IdentityError UserAlreadyHasPassword()
{
return this.GetErrorByCode("UserAlreadyHasPassword");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating user lockout is not enabled.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating user lockout is not enabled..</returns>
public override IdentityError UserLockoutNotEnabled()
{
return this.GetErrorByCode("UserLockoutNotEnabled");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a user is already in the specified <paramref name="role" />.
/// </summary>
/// <param name="role">The duplicate role.</param>
/// <returns>An <see cref="IdentityError" /> indicating a user is already in the specified <paramref name="role" />.</returns>
public override IdentityError UserAlreadyInRole(string role)
{
return this.FormatErrorByCode("UserAlreadyInRole", (object)role);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a user is not in the specified <paramref name="role" />.
/// </summary>
/// <param name="role">The duplicate role.</param>
/// <returns>An <see cref="IdentityError" /> indicating a user is not in the specified <paramref name="role" />.</returns>
public override IdentityError UserNotInRole(string role)
{
return this.FormatErrorByCode("UserNotInRole", (object)role);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password of the specified <paramref name="length" /> does not meet the minimum length requirements.
/// </summary>
/// <param name="length">The length that is not long enough.</param>
/// <returns>An <see cref="IdentityError" /> indicating a password of the specified <paramref name="length" /> does not meet the minimum length requirements.</returns>
public override IdentityError PasswordTooShort(int length)
{
return this.FormatErrorByCode("PasswordTooShort", (object)length);
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password entered does not contain a non-alphanumeric character, which is required by the password policy.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a password entered does not contain a non-alphanumeric character.</returns>
public override IdentityError PasswordRequiresNonAlphanumeric()
{
return this.GetErrorByCode("PasswordRequiresNonAlphanumeric");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password entered does not contain a numeric character, which is required by the password policy.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a password entered does not contain a numeric character.</returns>
public override IdentityError PasswordRequiresDigit()
{
return this.GetErrorByCode("PasswordRequiresDigit");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password entered does not contain a lower case letter, which is required by the password policy.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a password entered does not contain a lower case letter.</returns>
public override IdentityError PasswordRequiresLower()
{
return this.GetErrorByCode("PasswordRequiresLower");
}
/// <summary>
/// Returns an <see cref="IdentityError" /> indicating a password entered does not contain an upper case letter, which is required by the password policy.
/// </summary>
/// <returns>An <see cref="IdentityError" /> indicating a password entered does not contain an upper case letter.</returns>
public override IdentityError PasswordRequiresUpper()
{
return this.GetErrorByCode("PasswordRequiresUpper");
}
/// <summary>Returns a localized <see cref="IdentityError"/> for the provided code.</summary>
/// <param name="code">The error's code.</param>
/// <returns>A localized <see cref="IdentityError"/>.</returns>
private IdentityError GetErrorByCode(string code)
{
return new IdentityError()
{
Code = code,
Description = this.localizer.GetString(code)
};
}
/// <summary>Formats a localized <see cref="IdentityError"/> for the provided code.</summary>
/// <param name="code">The error's code.</param>
/// <param name="parameters">The parameters to format the string with.</param>
/// <returns>A localized <see cref="IdentityError"/>.</returns>
private IdentityError FormatErrorByCode(string code, params object[] parameters)
{
return new IdentityError
{
Code = code,
Description = string.Format(this.localizer.GetString(code, parameters))
};
}
}
And initialize everything:
Startup.cs
[...]
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddErrorDescriber<LocalizedIdentityErrorDescriber>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
// Your service configuration code
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
// Your service configuration code cont.
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// your configuration code
app.UseRequestLocalization(
new RequestLocalizationOptions()
{
DefaultRequestCulture = new RequestCulture("fr"),
SupportedCultures = SupportedCultures,
SupportedUICultures = SupportedCultures
});
app.UseStaticFiles();
app.UseIdentity();
// your configuration code
}
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With