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

AV0029: Remove unnecessary OpenAPI services

Value
Rule IDAV0029
CategoryUsage
Fix isNon-breaking

Cause

The OpenAPI services are registered alongside the versioned ones that replace them.

Rule Description

AddApiVersioning().AddOpenApi() registers services of its own in place of the ones OpenAPI registers for itself, which describe a single document that knows nothing about API versions. Calling AddOpenApi() on the service collection as well registers services that are then replaced.

Consider the following code:

var builder = WebApplication.CreateBuilder( args );

builder.Services.AddOpenApi();
builder.Services.AddApiVersioning().AddOpenApi();

The AddOpenApi() above belongs to OpenAPI itself and is superseded by the versioned one. Any of AddApiExplorer(), AddODataApiExplorer(), AddGrpcApiExplorer(), or AddOpenApi() on the API versioning builder has the same effect.

How to Fix Violations

Remove the call to AddOpenApi() on the service collection.

var builder = WebApplication.CreateBuilder( args );

builder.Services.AddApiVersioning().AddOpenApi();

See OpenAPI options for how the versioned documents are configured.

When to Suppress Warnings

It is safe to suppress this rule. The call is redundant rather than wrong.