Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

AV0014: Missing API behavior

Value
Rule IDAV0014
CategoryUsage
Fix isBreaking

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.