liveBook · Manning

Automatic 400 responses

As explained in ASP.NET Core in Action, 3e

Automatic 400 responses are framework-generated Bad Request responses produced when API model validation fails.

Automatic 400 responses let an ASP.NET Core API reject invalid model data before the controller action runs. Applying [ApiController] adds a filter that checks model validation and returns Bad Request automatically. section 20.4

Using [ApiController] also supplies related API conventions:

  • Attribute routing is required. section 20.4
  • Complex action parameters are inferred from the request body, so JSON input typically needs no explicit [FromBody]. section 20.4
  • Error responses can use ProblemDetails for consistent error data. section 20.4

Manual validation versus automatic validation

Without [ApiController], an action checks ModelState.IsValid and returns BadRequest(new ValidationProblemDetails(ModelState)). With [ApiController], that validation code can be removed; an invalid UpdateModel containing a missing required Name receives a 400 response automatically.

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains the validation filter and contrasts automatic handling with manual ModelState checks, but does not detail filter internals.
Examples
Uses a FruitController Update action with UpdateModel, a required Name property, and contrasting manual and automatic validation.
What it assumes
Assumes familiarity with API controllers and model validation while showing the manual ModelState pattern for comparison.
What you can do after
Apply it via the [ApiController] attribute and customize it through ConfigureApiBehaviorOptions when necessary.
How it connects
Connects model validation with ModelState, [ApiController], model binding, attribute routing, and ProblemDetails.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.