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

AV0013: Missing AddMvc

Value
Rule IDAV0013
CategoryUsage
Fix isBreaking

Cause

An application uses MVC controllers and API versioning, but never opted into versioning MVC.

Rule Description

API versioning covers minimal APIs on its own. Controllers are discovered and routed by MVC, which requires an explicit opt in so that the versioning metadata declared on a controller is applied to the actions it defines. Without it, the attributes are still compiled but nothing ever reads them.

Consider the following code:

var builder = WebApplication.CreateBuilder( args );

builder.Services.AddControllers();
builder.Services.AddApiVersioning();

AddControllers() opts into MVC and AddApiVersioning() opts into API versioning, but neither versions the other. Every controller in the application is routed as if it declared no API version at all.

How to Fix Violations

Call AddMvc() on the builder returned by AddApiVersioning().

var builder = WebApplication.CreateBuilder( args );

builder.Services.AddControllers();
builder.Services.AddApiVersioning().AddMvc();

AddMvcCore() opts into MVC the same way AddControllers() does and requires the same call.

When to Suppress Warnings

It is safe to suppress this rule only if the controllers in the application are deliberately left unversioned; for example, when API versioning was added for Minimal APIs and the controllers serve something else. Note that AddApiVersioning().AddMvc() changes how requests are routed to controllers, so applying the fix to an existing service is a breaking change for clients that do not send a version.