Use web API analyzers

ASP.NET Core 2.2 and later provides an MVC analyzers package intended for use with web API projects. The analyzers work with controllers annotated with ApiControllerAttribute, while building on web API conventions.

The analyzers package notifies you of any controller action that:

  • Returns an undeclared status code.
  • Returns an undeclared success result.
  • Documents a status code that isn't returned.
  • Includes an explicit model validation check.

Reference the analyzer package

In ASP.NET Core 3.0 or later, the analyzers are included in the .NET Core SDK. To enable the analyzer in your project, include the IncludeOpenAPIAnalyzers property in the project file:


Package installation

Install the Microsoft.AspNetCore.Mvc.Api.Analyzers NuGet package with one of the following approaches:

From the Package Manager Console window:

  • Go to View > Other Windows > Package Manager Console.

  • Navigate to the directory in which the ApiConventions.csproj file exists.

  • Execute the following command:

    Install-Package Microsoft.AspNetCore.Mvc.Api.Analyzers

Analyzers for web API conventions

OpenAPI documents contain status codes and response types that an action may return. In ASP.NET Core MVC, attributes such as ProducesResponseTypeAttribute and ProducesAttribute are used to document an action. ASP.NET Core web API documentation with Swagger / OpenAPI goes into further detail on documenting your web API.

One of the analyzers in the package inspects controllers annotated with ApiControllerAttribute and identifies actions that don't entirely document their responses. Consider the following example:

// GET api/contacts/{guid}
[HttpGet("{id}", Name = "GetById")]
[ProducesResponseType(typeof(Contact), StatusCodes.Status200OK)]
public IActionResult Get(string id)
    var contact = _contacts.Get(id);

    if (contact == null)
        return NotFound();

    return Ok(contact);

The preceding action documents the HTTP 200 success return type but doesn't document the HTTP 404 failure status code. The analyzer reports the missing documentation for the HTTP 404 status code as a warning. An option to fix the problem is provided.

analyzer reporting a warning

Additional resources