The [ApiController]
attribute enables a few features including attribute routing requirement, automatic model validation and binding source parameter inference.
This was taken straight from the MS docs Create web APIs with ASP.NET Core:
The [ApiController] attribute can be applied to a controller class to
enable the following opinionated, API-specific behaviors:
- Attribute routing requirement
- Automatic HTTP 400 responses
- Binding source parameter inference
- Multipart/form-data request inference
- Problem details for error status codes
The Problem details for error
status codes feature requires a compatibility version of 2.2 or later.
The other features require a compatibility version of 2.1 or later.
Some details on the features below:
Attribute routing
Attribute routing will be required if you use [ApiController]
, eg:
[ApiController]
[Route("[controller]")]
public class DataTablesController: ControllerBase
Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure
Automatic Http 400 responses
Adds an action filter to return 400 response if the ModelState
fails validation. You no longer need to write this in your actions, it will be handled automatically:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Binding source parameter inference
Again, from the linked docs:
A binding source attribute defines the location at which an action
parameter's value is found. The following binding source attributes
exist: [FromBody]
, [FromForm]
, [FromHeader]
, [FromQuery]
, [FromRoute]
, [FromServices]
Multipart/form-data request inference
The [ApiController] attribute applies an inference rule when an action
parameter is annotated with the [FromForm] attribute. The
multipart/form-data request content type is inferred.
An example using binding source parameter inference:
[HttpPost]
public IActionResult Test([FromForm] Model model)
{
return Ok("test");
}
ApiBehaviorApplicationModelProvider
(source), and behavior can be customized viaApiBehaviorOptions
(source), which is accessible from the container through the options pattern. – Kosey