In ASP.NET Core 10 with AddValidation, how are nested objects and collection items in a Minimal API request body validated, and how are failures keyed?
answer
- recursion through generated type metadata
- each non-null collection item
- keys like Passengers[1].FullName
- property errors skip IValidatableObject
- ValidationOptions.MaxDepth = 32
basics
~20 sThe filter walks the body's object graph using generated metadata, validating each nested object and each non-null collection item, and reports every failure in one 400 keyed by its path, such as Passengers[1].FullName; graphs deeper than MaxDepth (32) throw.
solid answer
~40 sFor a body type, the generated `ValidatableTypeInfo` validates each property's attributes, then descends: a nested object is validated as its own type, and for an `IEnumerable` property every non-null item is validated, with the path extended to `Passengers[0]`, `Passengers[1]` and so on. Errors are collected, not stopped at the first, and keyed by that path, so a missing name on the second passenger is reported under `Passengers[1].FullName`. Within one object, a failing `[Required]` skips the property's other attributes, and any property error skips the type-level attributes and `IValidatableObject.Validate` for that object. Base types and `[JsonDerivedType]` subtypes are covered. Each level of nesting counts against `ValidationOptions.MaxDepth`, 32 by default; exceeding it throws `InvalidOperationException`, usually a sign of a cyclic graph.
code
csharp · 14 linespublic sealed class SeatReservation
{
[Required, StringLength(8)]
public string? TrainNumber { get; set; }
public List<Passenger> Passengers { get; set; } = [];
}
public sealed class Passenger
{
[Required(ErrorMessage = "Passenger name is required.")]
public string? FullName { get; set; }
[Range(0, 120, ErrorMessage = "Age must be between 0 and 120.")]
public int Age { get; set; }
}go deeper
Recall that AddValidation checks nested objects and every item of a collection, and that errors come back keyed by a path such as Passengers[1].FullName.
Explain the traversal order, the Required and property-error short-circuits, how keys are built, and what null items and MaxDepth do.
Anticipate production surprises: cross-field rules hidden behind field errors, null items slipping through, cyclic graphs turning into 500s, and clients that must map PascalCase paths onto their own fields.
Choose how much of a request's shape the edge validates: deep declarative graphs are convenient but couple the API contract to model classes, so decide which rules live on DTOs and which in the domain.
## The object graph the filter walks When `AddValidation()` is on, the source generator emits a **`ValidatableTypeInfo`** for each request type it discovers, listing the members that carry validation attributes or lead to types that do. Validation of a body parameter then proceeds recursively: 1. Validate attributes on the parameter itself. 2. Validate each property of the object: its attributes first, then its value. 3. If the property's value is a **complex object**, validate it the same way, one level deeper. 4. If it is an **`IEnumerable`**, validate each non-null item as its own object. 5. After the properties, validate **type-level attributes**, then call `IValidatableObject.Validate` if the type implements it. Base classes are walked as part of the derived type, and subtypes declared with `[JsonDerivedType]` are discovered so that a polymorphic body is validated by its runtime type. ## The rail-booking reservation ```csharp public sealed class SeatReservation { [Required, StringLength(8)] public string? TrainNumber { get; set; } public List<Passenger> Passengers { get; set; } = []; } public sealed class Passenger { [Required(ErrorMessage = "Passenger name is required.")] public string? FullName { get; set; } [Range(0, 120, ErrorMessage = "Age must be between 0 and 120.")] public int Age { get; set; } } ``` Posting a reservation whose first passenger has `Age: 140` and whose second has no `FullName` produces one 400 with both errors. ## How failures are keyed | Where the rule sits | Error key | |---|---| | a handler parameter `carriage` | `carriage` | | a property of the body object | `TrainNumber` | | a property of a collection item | `Passengers[1].FullName` | | a nested object's property | `Contact.Email` (path joined with dots) | | a type-level attribute without member names | the object's own path | Keys use the CLR property names joined by `.` with `[index]` for collection items. The body parameter's own name is not prefixed; a collection parameter's name is (`passengers[0].FullName` for a `List<Passenger> passengers` parameter). ## Short-circuits inside one object - A failing **`[Required]`** on a property skips that property's other attributes; there is no point checking the length of a missing value. - If **any property** of an object failed, its type-level attributes and `IValidatableObject.Validate` are skipped. Cross-field rules therefore run only on objects whose individual fields are valid. - Other objects are not affected: every passenger is still validated, and all errors from all parameters are returned together. ## Nulls and depth - A **null nested object** or a null collection item is skipped, not reported; put `[Required]` on the property if it must be present. - Each nested level increases the current depth. When it reaches `ValidationOptions.MaxDepth` (**32** by default), validation throws `InvalidOperationException` naming the path, which surfaces as a server error rather than a 400. The usual cause is a cyclic object graph; a genuinely deep but finite graph can raise the limit with `AddValidation(o => o.MaxDepth = 64)`. - `[SkipValidation]` on a property stops descent into it (experimental in 10, diagnostic ASP0029). ## What interviewers listen for - That nested objects and collection items are validated, with all errors in one response. - The path format of the error keys. - The ordering rule that hides `IValidatableObject` errors until field-level errors are fixed. - What `MaxDepth` protects against and how it fails.
- Why might a client fix every field error and then receive a brand-new error from the same request object?Because `IValidatableObject.Validate` and type-level attributes run only when all property-level checks on that object passed. A cross-field rule, such as a return date after the outbound date, stays silent while a field error exists and appears once the fields are fixed. Document this or move cross-field rules into property-independent checks if clients need everything at once.
- A reservation body arrives with a null element in Passengers. Is it reported?No. The traversal skips null collection items and null nested objects. If null passengers must be rejected, enforce it in a type-level rule on `SeatReservation` (an `IValidatableObject.Validate` that checks the list) or check for null items in the handler.
- Built-in Minimal API validation checks only top-level properties of the body.
- Validation stops at the first failing passenger and reports only that one.
- IValidatableObject.Validate always runs, even when property errors exist.
- Exceeding MaxDepth quietly treats deeper members as valid.
- A null collection item is reported as a Required error automatically.
Assumes ASP.NET Core 10: Minimal API validation with nested and collection traversal arrived with AddValidation in 10; MaxDepth defaults to 32 in Microsoft.Extensions.Validation 10.0.