For ASP.NET Core with .NET 9, based on @LazZiya's answer and the asp.net docs on how to resolve a service at app startup, this is how I did it in the Program.cs file:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
(source)
File SharedResource.en.resx in the Resources/ path.
Name | en |
---|---|
Validation_ValueMustNotBeNull | The field '{0}' is required. |
Validation_AttemptedValueIsInvalid | The value '{0}' is not valid for the field '{1}'. |
var app = builder.Build();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var localizer = services.GetRequiredService<IStringLocalizer<SharedResource>>();
var options = services.GetRequiredService<IOptions<MvcOptions>>().Value;
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((field) => localizer["Validation_ValueMustNotBeNull", field]);
options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((value, field) => localizer["Validation_AttemptedValueIsInvalid", value, field]);
// ...
}
You can check here all the available properties you can override.