79614308

Date: 2025-05-09 14:18:18
Score: 0.5
Natty:
Report link

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:

  1. Configure localization services:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

(source)

  1. Create the resource files

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}'.
  1. Override the default model binding error messages:
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.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @LazZiya'sand
  • Low reputation (1):
Posted by: John Jones