In ASP.NET Core, what does the [ApiController] attribute change about a controller's actions, and how do you switch each behaviour off?
answer
- conventions, not a base class
- attribute routing becomes mandatory
- binding sources inferred: services, body, route, query
- bare 4xx results become ProblemDetails
- ApiBehaviorOptions Suppress* flags
basics
~20 s[ApiController] makes attribute routing mandatory, returns an automatic 400 for invalid model state, infers parameter binding sources, adds a multipart/form-data constraint for form files and turns bare 4xx results into ProblemDetails; ApiBehaviorOptions switches each off.
solid answer
~40 s`[ApiController]` applies a set of API conventions to every action of the controller (or of the assembly, when applied with `[assembly: ApiController]`). An action without an attribute route makes MVC throw an `InvalidOperationException`. Invalid model state short-circuits into a 400 `ValidationProblemDetails`. Parameters get inferred sources: a complex type registered in DI comes from services, another complex type from the body, a name in the route template from the route, everything else from the query, and two body parameters throw. `IFormFile` parameters add a `multipart/form-data` consumes constraint. Status-code-only results of 400 or more, such as `NotFound()`, become `ProblemDetails`. In .NET 10 cookie authentication also answers these endpoints with 401/403 instead of a login redirect. The switches live on `ApiBehaviorOptions`: `SuppressModelStateInvalidFilter`, `SuppressInferBindingSourcesForParameters`, `DisableImplicitFromServicesParameters`, `SuppressConsumesConstraintForFormFileParameters` and `SuppressMapClientErrors`.
code
csharp · 19 lines[ApiController]
[Route("api/claims")]
public class ClaimsController(IClaimStore store) : ControllerBase
{
// id: in the route template -> bound from the route
// includeNotes: simple, not in the route -> bound from the query
[HttpGet("{id:int}")]
public async Task<ActionResult<ClaimDto>> Get(int id, bool includeNotes, CancellationToken ct)
=> await store.FindAsync(id, includeNotes, ct) is { } claim ? claim : NotFound();
// NewClaim: complex, not a service -> bound from the body
// IClaimStore would be inferred from services if it were a parameter
[HttpPost]
public async Task<IActionResult> Submit(NewClaim claim, CancellationToken ct)
{
await store.AddAsync(claim, ct);
return NoContent();
}
}go deeper
Recall that [ApiController] requires attribute routes and returns a 400 automatically when the model is invalid.
Walk through the inference rules in order, the bare-status-to-ProblemDetails mapping and the ApiBehaviorOptions flag that disables each behaviour.
Debug the surprises: a DI-registered type pulled from services instead of the body, two inferred bodies throwing, and .NET 10's 401 instead of a login redirect.
Decide which conventions a platform keeps globally, applying the attribute at assembly level and documenting every opt-out so APIs stay consistent.
## What the attribute is `[ApiController]` (`Microsoft.AspNetCore.Mvc.ApiControllerAttribute`) is a marker that MVC's `ApiBehaviorApplicationModelProvider` looks for while it builds the application model. It is not a base class and adds no members: it switches on **conventions** for every action of the marked controller. Its `AttributeUsage` allows it on a class (inherited by subclasses, so a shared `ApiControllerBase` can carry it) or on the whole assembly with `[assembly: ApiController]`. ## The behaviours it turns on | Behaviour | What you observe | Opt-out on `ApiBehaviorOptions` | |---|---|---| | Attribute routing required | an action with no `[Route]`/`[HttpGet(...)]` on it or its controller makes MVC throw `InvalidOperationException` | none: add a route | | Automatic 400 | invalid `ModelState` returns `ValidationProblemDetails` before the action runs | `SuppressModelStateInvalidFilter` | | Binding-source inference | parameters need no `[From*]` in the common cases | `SuppressInferBindingSourcesForParameters`, `DisableImplicitFromServicesParameters` | | Form-file consumes constraint | an action with an `IFormFile` parameter accepts only `multipart/form-data` requests; another content type gets 415 | `SuppressConsumesConstraintForFormFileParameters` | | Client-error mapping | `NotFound()`, `Conflict()`, `BadRequest()` and other bare status results of 400 or more get a `ProblemDetails` body | `SuppressMapClientErrors` | | No cookie login redirect (.NET 10) | cookie authentication answers 401/403 instead of 302 to the login page | `[AllowCookieRedirect]` on the endpoint | The options are configured once for the app: ```csharp builder.Services.AddControllers() .ConfigureApiBehaviorOptions(o => { o.SuppressMapClientErrors = true; // keep bare 404s empty o.DisableImplicitFromServicesParameters = true; }); ``` ## Binding-source inference in detail The `InferParameterBindingInfoConvention` only fills in a source for parameters that do not already have one, applying these rules in order: 1. A **complex type that is registered in DI** (checked through `IServiceProviderIsService`) is bound from services, as if it had `[FromServices]`, unless `DisableImplicitFromServicesParameters` is `true`. 2. Any **other complex type** is bound from the body, unless the type declares its own binding sources on its properties. 3. A simple parameter whose **name appears in any attribute route template** of the action is bound from the route. 4. **Everything else** is bound from the query string. `IFormFile` and `IFormFileCollection` already carry a form source, and `CancellationToken` carries a special source, so neither is inferred. If two parameters end up bound from the body, explicitly or by inference, MVC throws an `InvalidOperationException` that lists them and suggests `[FromQuery]`, `[FromRoute]` or `[FromBody]`. A body parameter that is optional (nullable or with a default value) is allowed to be empty. ## Client-error mapping in detail The mapping only touches results that implement `IClientErrorActionResult` with a status of 400 or more. `StatusCodeResult` and its subclasses do (`NotFoundResult`, `ConflictResult`, `BadRequestResult`, `UnauthorizedResult`, `UnprocessableEntityResult`); object results do not. So in a claims API: - `return NotFound();` sends a 404 with `application/problem+json` holding `type`, `title: "Not Found"`, `status: 404` and a `traceId`. - `return NotFound(new { claimId = id });` sends your object unchanged, because a `NotFoundObjectResult` is an `ObjectResult`, not a bare status code. ## The .NET 10 addition `ApiControllerAttribute` implements `IDisableCookieRedirectMetadata` in ASP.NET Core 10. When cookie authentication challenges or forbids a request to such an endpoint, it sets 401 or 403 instead of redirecting to `LoginPath` or `AccessDeniedPath`; the `Location` header is still written. An endpoint that really wants the redirect adds `[AllowCookieRedirect]`, whose `IAllowCookieRedirectMetadata` wins regardless of order. In .NET 8 and 9 the same API answered with a 302 to the login page, which API clients had to detect and work around. ## Applying it selectively The options are global, but the attribute is not. A team can put `[ApiController]` on a shared base class for the public API and leave an internal callback controller without it, so that controller keeps conventional routing and reads its parameters through the classic binding rules. The automatic 400 comes from a `ModelStateInvalidFilter` that runs early among the action filters, so a custom validation filter that must see invalid models needs either `SuppressModelStateInvalidFilter = true` or a lower `Order`. When you switch a behaviour off globally, say so in the API guidelines: a reader who sees `[ApiController]` assumes all of the conventions above are active. ## What it does not do - It does not authenticate or authorize anything; `[Authorize]` and the policies do that. - It does not change the serializer or add XML support; formatters are configured on `AddControllers()`. - It does not wrap exceptions in ProblemDetails; an unhandled exception goes to the exception-handling middleware. - It does not apply to Minimal API endpoints, which have their own parameter inference and, in .NET 10, their own validation.
- Why does NotFound(new { claimId }) not get a ProblemDetails body while NotFound() does?The client-error filter only rewrites results that implement `IClientErrorActionResult`, which `StatusCodeResult` and its subclasses such as `NotFoundResult` do. `NotFound(value)` returns a `NotFoundObjectResult`, an `ObjectResult` that already has a body, so it is written as-is.
- A colleague registers a complex options-like class in DI and is surprised a POST action stops reading it from the body. Why?Under `[ApiController]`, a complex parameter whose type `IServiceProviderIsService` reports as registered is inferred from services before the body rule is tried. Mark the parameter `[FromBody]`, or set `DisableImplicitFromServicesParameters = true` to turn that inference off for the app.
- Can [ApiController] be applied once for the whole project?Yes. Its `AttributeUsage` includes the assembly, so `[assembly: ApiController]` applies the conventions to every controller in that assembly, and the attribute is inherited, so a shared base controller can carry it. Every action then needs an attribute route.
- [ApiController] is what makes a class a controller that returns JSON.
- Under [ApiController], conventional routes from MapControllerRoute still reach the actions.
- [ApiController] turns NotFound(someObject) into a ProblemDetails body.
- [ApiController] makes unhandled exceptions come back as ProblemDetails.
- Every complex parameter of an [ApiController] action is always bound from the body.
Assumes ASP.NET Core 10: [ApiController] endpoints now carry IDisableCookieRedirectMetadata, so cookie authentication returns 401/403 instead of a login redirect; .NET 8 and 9 redirected.