AV0014: Missing API behavior
| Value | |
|---|---|
| Rule ID | AV0014 |
| Category | Usage |
| Fix is | Breaking |
Cause
A controller that serves an API has not opted into API behavior.
Rule Description
A controller derived from ControllerBase may serve an API or something else entirely. [ApiController] is what
resolves that ambiguity. It also turns on the conventions an API is expected to follow, such as automatic model
validation and problem details for error responses, which is how a versioning error is reported in the shape a client
can read.
A controller derived from Controller is assumed to serve a user interface rather than an API and is never reported.
Consider the following code:
[ApiVersion( 2.0 )]
[Route( "[controller]" )]
public class ExampleController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok();
}
The controller declares an API version but never states that it is an API.
How to Fix Violations
Add [ApiController] to the controller.
[ApiController]
[ApiVersion( 2.0 )]
[Route( "[controller]" )]
public class ExampleController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok();
}
The attribute can also be applied to the assembly, in which case it covers every controller and nothing is reported:
[assembly: ApiController]
When to Suppress Warnings
It is safe to suppress this rule if the controller derives from ControllerBase but does not serve an API. Applying
[ApiController] changes model binding and error responses, so adding it to an existing service is a breaking change
for clients that depend on the current behavior.