In ASP.NET Core MVC, how does AddDataAnnotationsLocalization translate validation messages, and why does a bare [Required] still render in English?
answer
- the ErrorMessage text is the key
- localizer for the model's declaring type
- DataAnnotationLocalizerProvider for a shared file
- ErrorMessageResourceType bypasses the localizer
- MVC and Razor Pages only in 10
basics
~10 sAddDataAnnotationsLocalization makes MVC look up each attribute's ErrorMessage, and [Display] names, through IStringLocalizer for the model's type. Only an explicit ErrorMessage is a key; a bare [Required] keeps the runtime's built-in English message.
solid answer
~40 s`AddDataAnnotationsLocalization()` on the MVC builder calls `AddLocalization` and sets `MvcDataAnnotationsLocalizationOptions.DataAnnotationLocalizerProvider`, by default `factory.Create(modelType)` for the class that declares the property. When a validation attribute fails, MVC uses that localizer only if the attribute has a non-empty `ErrorMessage` and neither `ErrorMessageResourceName` nor `ErrorMessageResourceType`; the `ErrorMessage` text is the key and the display name, plus values such as a range's minimum and maximum, are the format arguments. A bare `[Required]` has no `ErrorMessage`, so MVC calls `FormatErrorMessage` and the runtime's default text appears. `[Display(Name = ...)]` is translated by the same localizer. Point `DataAnnotationLocalizerProvider` at a `SharedResource` to keep messages in one file. In ASP.NET Core 10 this applies to MVC and Razor Pages; Minimal API validation via `AddValidation` does not use it.
code
csharp · 17 linespublic sealed class OrderForm
{
[Display(Name = "Vintage")]
[Required(ErrorMessage = "The {0} field is required.")]
[Range(1950, 2025, ErrorMessage = "{0} must be between {1} and {2}.")]
public int? Vintage { get; set; }
[Required] // no ErrorMessage: the runtime's default English text
public string? Email { get; set; }
}
// Program.cs
builder.Services.AddRazorPages()
.AddViewLocalization(o => o.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization(o =>
o.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource)));go deeper
Recall that AddDataAnnotationsLocalization goes on the MVC builder and that each attribute needs an ErrorMessage, which becomes the key in the .resx.
Explain the three conditions for using the localizer, which type's resource is searched, and how display names feed the {0} argument.
Separate the message sources: attribute messages, bare defaults, model-binding errors and IValidatableObject results, and centralize them with DataAnnotationLocalizerProvider.
Decide how validation text is owned when MVC pages and .NET 10 Minimal APIs coexist, given that in .NET 10 only MVC's pipeline consults the localizer.
## What the call wires up DataAnnotations localization is an MVC feature, added on the builder returned by `AddControllers()`, `AddControllersWithViews()` or `AddRazorPages()`: ```csharp builder.Services.AddControllersWithViews() .AddViewLocalization() .AddDataAnnotationsLocalization(); ``` `AddDataAnnotationsLocalization` does two things: - calls `AddLocalization()`, so `IStringLocalizerFactory` exists; - configures `MvcDataAnnotationsLocalizationOptions.DataAnnotationLocalizerProvider`, a `Func<Type, IStringLocalizerFactory, IStringLocalizer>`. The default is `(type, factory) => factory.Create(type)`. The `Type` passed in is the **container type**, the class that declares the property (or the model type itself for a top-level parameter). A property on `WineShop.Models.OrderForm` is therefore translated from `Resources/Models/OrderForm.fr.resx` when `ResourcesPath` is `"Resources"`. ## The rule that decides whether a message is localized MVC's validator adapters apply the localizer only when **all three** hold: 1. `ErrorMessage` is set and not empty; 2. `ErrorMessageResourceName` is empty; 3. `ErrorMessageResourceType` is `null`. Then the message is `localizer[attribute.ErrorMessage, arguments]`. The arguments depend on the attribute: the display name for `[Required]`, the display name plus `Minimum` and `Maximum` for `[Range]`. A French `.resx` entry for `{0} must be between {1} and {2}.` can reorder them freely. Otherwise MVC uses the attribute's own `FormatErrorMessage`. That is why: - **a bare `[Required]`** shows the runtime's built-in default message, untouched by your `.resx` files; - **`ErrorMessageResourceType = typeof(Messages)`** keeps working the classic way, through a strongly typed resource class, and never reaches `IStringLocalizer`. The usual convention is to give every attribute an explicit English `ErrorMessage` and use that sentence as the key. ## One failure, step by step A French customer submits the wine-order form with `Vintage = 1890`: 1. `[Range(1950, 2025)]` fails during MVC model validation. 2. The range adapter sees an `ErrorMessage` and no resource name or type, so it uses the localizer. 3. The localizer looks up the key `{0} must be between {1} and {2}.` in the French resource and finds `{0} doit être compris entre {1} et {2}.`. 4. The first argument is the display name, itself translated from `Vintage` to `Millésime`; the others are 1950 and 2025. 5. `ModelState` receives "Millésime doit être compris entre 1950 et 2025.", which the view shows next to the field. ## Display names and enums The metadata provider uses the same localizer for `[Display(Name = ...)]` and `[Display(Description = ...)]` when `ResourceType` is not set, and for `[Display]` names on enum members. Because the display name is also the `{0}` argument of most messages, translating `Vintage` to `Millésime` changes both the label and the error. The same adapters produce the `data-val-*` attributes that unobtrusive client-side validation reads, so translated messages reach the browser too. ## One file for every model Per-model files multiply quickly. Point the provider at a shared resource instead: ```csharp .AddDataAnnotationsLocalization(o => o.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource))); ``` All validation messages and display names are then looked up in `SharedResource.fr.resx` and `SharedResource.de.resx`. Keep `SharedResource` in the root namespace, or the doubled-folder naming trap applies. ## Messages it does not touch | Message | Source | Localized by `AddDataAnnotationsLocalization`? | |---|---|---| | `[Required(ErrorMessage = "...")]` | validation attribute | yes | | bare `[Required]` | runtime default text | no | | "The value 'abc' is not valid for Vintage." | model binding | no; `MvcOptions.ModelBindingMessageProvider` | | `IValidatableObject` results | your code | no; localize them yourself | ## Version notes In ASP.NET Core 10 the feature belongs to MVC and Razor Pages. Minimal APIs' built-in validation, registered with `AddValidation()`, and Blazor's `DataAnnotationsValidator` do not consult `IStringLocalizer`. The documentation describes localization for that validation pipeline under ASP.NET Core 11, which is a preview release and not something a .NET 10 app has. ## Mistakes interviewers listen for - expecting a bare `[Required]` to pick up a `.resx` entry; - mixing `ErrorMessageResourceType` with the localizer and expecting both; - using the property name rather than the `ErrorMessage` text as the key; - expecting the binding error for unparsable input to come from the same resource.
- A German customer types "abc" into Vintage and sees "The value 'abc' is not valid for Vintage." in English. Why, and where is it fixed?That message is a model-binding error, raised before any validation attribute runs, so `AddDataAnnotationsLocalization` never sees it. It comes from `MvcOptions.ModelBindingMessageProvider`; set accessors such as `SetAttemptedValueIsInvalidAccessor` to functions that look the text up in a localizer, which reads the UI culture at call time.
- Does AddDataAnnotationsLocalization translate messages for a .NET 10 Minimal API that uses AddValidation?No. It configures MVC's validator and metadata providers, which Minimal APIs do not use. In ASP.NET Core 10, `AddValidation` reports the attributes' own formatted messages. Localizing that pipeline is documented only for the ASP.NET Core 11 preview.
- AddDataAnnotationsLocalization translates the built-in message of a bare [Required].
- With ErrorMessageResourceType set, the IStringLocalizer lookup is tried first.
- The localizer key is the property name, not the ErrorMessage text.
- In .NET 10 the call also localizes Minimal API validation registered with AddValidation.
- "The value 'abc' is not valid" comes from a DataAnnotations attribute.
Assumes ASP.NET Core 10: AddDataAnnotationsLocalization covers MVC and Razor Pages only, and localization for Minimal API AddValidation appears only in the ASP.NET Core 11 preview documentation.