Skip to content

10.4 — [ApiController]: What It Actually Changes

← Roadmap · Section: 10. Web API Design and REST Prev: 10.3 Status codes · Next: 10.5 Content negotiation and JSON

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

[ApiController] is an attribute that switches on a bundle of API-specific conventions, so you stop writing the same boilerplate in every action.

  • Automatic 400 on invalid models — if (!ModelState.IsValid) becomes dead code.
  • Inferred binding sources — complex types come from the body, simple types from the route or query, with no [FromBody] needed.
  • Attribute routing becomes mandatory — the app throws at startup without it.
  • Errors become ProblemDetails instead of a bare status code.

Definitions

Term What it is What it means
[ApiController] a C# attribute Applies a set of API conventions to a controller.
ControllerBase a base class The API base class — no view support. Required for [ApiController].
Binding source inference a convention The framework decides where each parameter comes from.
ModelState a property The record of what model binding and validation found.
Automatic model validation a filter A built-in action filter that short-circuits with 400 on invalid input.
ProblemDetails a class (RFC 7807) The standard machine-readable error body.
ValidationProblemDetails a class ProblemDetails plus a per-field errors dictionary.
InvalidModelStateResponseFactory a delegate option Hook to customise that automatic 400.
SuppressModelStateInvalidFilter an option Turns automatic validation off.
[FromBody] an attribute Bind from the request body. Inferred for complex types.
[FromServices] an attribute Bind from DI. Inferred in .NET 7+.

The concept

Before [ApiController], every API action opened the same way:

[HttpPost]
public IActionResult Create([FromBody] CreateOrderRequest request)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);      // ← in every single action

    // ...
}

Two pieces of ceremony repeated everywhere: [FromBody], which is nearly always what you meant, and the ModelState check, which is nearly always the same three lines.

[ApiController] says: this controller is an API, apply the API conventions. Both disappear.

[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(CreateOrderRequest request)   // no [FromBody], no check
    {
        // If we are executing at all, the model is valid.
    }
}

⚠️ The risk is that conventions are invisible. When a 400 appears that you did not write, or a parameter binds from somewhere unexpected, the cause is a convention you cannot see in the code. Knowing what it turns on is what turns it from magic into a tool.


How it works

The five behaviours

Behaviour Effect
1. Attribute routing required Conventional routes no longer reach this controller — and the app throws at startup if an action has no route attribute.
2. Automatic 400 responses An action filter short-circuits before your code runs when ModelState is invalid.
3. Binding source inference Complex types → body; simple types → route or query; IFormFile → form.
4. Multipart/form-data inference [FromForm] parameters imply the form content type.
5. ProblemDetails for error codes NotFound() and friends return an RFC 7807 body, not an empty one.

1 — Routing becomes mandatory, on purpose

[ApiController]
public class OrdersController : ControllerBase
{
    [HttpGet]                    // ⚠️ No route template anywhere → InvalidOperationException at startup
    public IActionResult Get() => Ok();
}

The reason is deliberate: conventional routing derives public URLs from method names, so renaming Get to GetAll silently changes your published API. For a controller serving other systems, that is unacceptable — the URL should be written down (8.3).

✅ Failing at startup is the good outcome. You find out on dotnet run, not from a 404 in production.

2 — Automatic model validation

An action filter runs before your action. If ModelState is invalid it short-circuits with 400 and a ValidationProblemDetails body:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-8fa1c...-00",
  "errors": {
    "Email":    [ "The Email field is not a valid e-mail address." ],
    "Quantity": [ "The field Quantity must be between 1 and 100." ]
  }
}

⚠️ ModelState invalid does not only mean "failed a data annotation". It also covers binding failures — sending "abc" for an int, or malformed JSON. So an action can return 400 for reasons that have nothing to do with your validation attributes (11.5).

⚠️ It runs before your action, so if (!ModelState.IsValid) inside the action is dead code. Harmless, but it misleads the next reader into thinking validation is handled there.

⚠️ And it does not validate anything you construct yourself. Apply a JSON Patch, map to a new object, or mutate the model — none of that is revalidated unless you call TryValidateModel (10.2).

Customising the response, which comes up when a client expects a legacy error shape:

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var problem = new ValidationProblemDetails(context.ModelState)
        {
            Status = StatusCodes.Status422UnprocessableEntity,   // 422 instead of 400
            Type   = "https://api.example.com/errors/validation",
            Instance = context.HttpContext.Request.Path
        };
        problem.Extensions["traceId"] = context.HttpContext.TraceIdentifier;

        return new UnprocessableEntityObjectResult(problem)
        {
            ContentTypes = { "application/problem+json" }
        };
    };
});

Or switch it off entirely — occasionally right when you need to inspect ModelState and decide:

builder.Services.Configure<ApiBehaviorOptions>(o => o.SuppressModelStateInvalidFilter = true);

⚠️ If you suppress it, you must write the check back into every action. Suppress it and forget, and invalid input reaches your code as nulls and zeroes.

3 — Binding source inference

The rules, in order:

Parameter Inferred source
Matches a route template token [FromRoute]
A complex type [FromBody]
Registered in DI (.NET 7+) [FromServices]
IFormFile / IFormFileCollection [FromForm]
Anything else (simple type) [FromQuery]
[HttpPut("{id:int}")]
public IActionResult Update(
    int id,                       // → route: matches {id}
    UpdateOrderRequest request,   // → body: complex type
    [FromQuery] bool notify,      // → query anyway, but explicit reads better
    IOrderService service)        // → DI (.NET 7+)

⚠️ Only one parameter can come from the body. Two complex parameters both infer [FromBody], and the app throws at startup — the body can only be read once. The fix is to wrap them in one request type.

⚠️ A complex type you wanted from the query is the classic surprise. A OrderQuery filter object infers [FromBody], so a GET with query-string parameters binds nothing and every property is null. [FromQuery] is required:

[HttpGet]
public IActionResult List([FromQuery] OrderQuery query)   // ⚠️ [FromQuery] is NOT optional here

⚠️ The DI inference in .NET 7+ has a sharp edge. If a type is registered in the container, a parameter of that type is bound from DI rather than the request — so registering something that is also a request model silently changes how it binds. [FromBody] explicitly overrides it.

4 and 5 — form inference and ProblemDetails

[FromForm] on a parameter implies multipart/form-data, so you do not need [Consumes].

And error status codes get a body. Without [ApiController], NotFound() returns 404 with nothing at all. With it:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-8fa1c...-00"
}

That traceId is genuinely useful — it correlates the client's error with your logs (18.4).

Turn it off if a client cannot cope with the shape:

builder.Services.Configure<ApiBehaviorOptions>(o => o.SuppressMapClientErrors = true);

The deeper detail — applying it once

Instead of decorating every controller, apply it at assembly level:

// In Program.cs or AssemblyInfo.cs
[assembly: ApiController]

⚠️ This affects every controller in the assembly, including MVC ones, which then break because attribute routing becomes mandatory and views stop working sensibly. Only do it in a project that is exclusively an API.

What it does not do, which is a good follow-up question:

  • ❌ Does not add authentication or authorization.
  • ❌ Does not set up CORS.
  • ❌ Does not force JSON — content negotiation is unchanged (10.5).
  • ❌ Does not handle exceptions. An unhandled exception is still a 500 (10.8).
  • ❌ Does not validate objects you build yourself after binding.

Code

[ApiController]
[Route("api/orders")]
[Produces("application/json")]
public sealed class OrdersController : ControllerBase
{
    private readonly IOrderService _orders;
    public OrdersController(IOrderService orders) => _orders = orders;

    // [FromQuery] is REQUIRED — OrderQuery is a complex type and would otherwise
    // infer [FromBody], leaving every property null on a GET.
    [HttpGet]
    public async Task<ActionResult<PagedResult<OrderDto>>> List(
        [FromQuery] OrderQuery query, CancellationToken ct)
        => Ok(await _orders.SearchAsync(query, ct));

    [HttpGet("{id:int}")]
    public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
    {
        var order = await _orders.FindAsync(id, ct);
        return order is null ? NotFound() : Ok(order);   // 404 now carries ProblemDetails
    }

    // No [FromBody] needed, and no ModelState check — if this runs, the model is valid.
    [HttpPost]
    [ProducesResponseType(typeof(OrderDto), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<OrderDto>> Create(
        CreateOrderRequest request, CancellationToken ct)
    {
        // ⚠️ Framework validation covers ANNOTATIONS. Business rules are still ours.
        if (await _orders.ReferenceExistsAsync(request.Reference, ct))
        {
            ModelState.AddModelError(nameof(request.Reference), "Reference is already in use.");
            return ValidationProblem(ModelState);        // same shape as the automatic 400
        }

        var created = await _orders.CreateAsync(request, ct);
        return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
    }
}

public sealed record CreateOrderRequest
{
    [Required, StringLength(50)]
    public string Reference { get; init; } = "";

    [Required, MinLength(1)]
    public IReadOnlyList<OrderLineRequest> Lines { get; init; } = [];

    [Range(0, 10_000)]
    public decimal DiscountAmount { get; init; }
}

The ValidationProblem(ModelState) call is the detail worth noticing. Business-rule failures that the framework cannot know about get returned in exactly the same shape as the automatic validation 400, so the client has one error format to parse rather than two.


Interview questions

Q: What does [ApiController] do?

It turns on a set of API conventions. The four that matter: automatic 400 responses when the model is invalid, so the ModelState.IsValid check disappears from every action; binding source inference, so complex types come from the body and simple types from the route or query without attributes; attribute routing becomes mandatory, and the app throws at startup without it; and error status codes come back as ProblemDetails rather than an empty body. It is not magic worth avoiding, but the conventions are invisible in the code, so knowing what they are is how you debug an unexpected 400.

Q: Why is attribute routing mandatory with it?

Because conventional routing derives URLs from method names, which means renaming a method silently changes your published API. For a controller other systems call, the URL is part of the contract and should be written down explicitly. It fails at startup rather than at request time, which is the right trade — you find out running the app locally, not from a 404 in production.

Q: What is the most common surprise with binding inference?

A complex type on a GET. A filter or query object is a complex type, so it infers [FromBody], and a GET with query-string parameters binds nothing — every property comes back null with no error. You need [FromQuery] explicitly. The other one is having two complex parameters on an action: both infer [FromBody], the body can only be read once, and the app throws at startup.

Q: What does [ApiController] not do?

It does not add authentication, authorization or CORS, it does not force JSON — content negotiation still works as normal — and it does not handle exceptions, so an unhandled exception is still a bare 500 unless you add an exception handler. It also does not validate objects you construct after binding, so applying a JSON Patch or mapping into a new object skips validation entirely unless you call TryValidateModel yourself.


Traps ⚠️

  • No route attribute → InvalidOperationException at startup.
  • Complex type on a GET without [FromQuery] binds nothing, silently.
  • Two complex parameters both infer [FromBody] → startup exception.
  • if (!ModelState.IsValid) inside the action is dead code — the filter already ran.
  • Suppressing the filter without restoring the checks lets invalid input through.
  • Assuming validation covers business rules. It covers annotations only.
  • Post-binding objects are not revalidated — patches and mappings skip it.
  • [assembly: ApiController] breaks MVC controllers in the same assembly.
  • .NET 7+ DI inference hijacks any parameter whose type is registered in the container.
  • Expecting exception handling. It does nothing for unhandled exceptions.


Sources