In an ASP.NET Core Web API, controller actions can optionally return a result value. If a controller action returns a value in the happy path, for example ControllerBase.Ok(Object), annotating the action with one of the [ProducesResponseType] overloads that describe the type is recommended.

Why is this an issue?

If an ASP.NET Core Web API uses Swagger, the API documentation will be generated based on the input/output types of the controller actions, as well as the attributes annotating the actions. If an action returns IActionResult or IResult, Swagger cannot infer the type of the response. From the consumer’s perspective, this can be confusing and lead to unexpected results and bugs in the long run without the API provider’s awareness.

This rule raises an issue on a controller action when:

How to fix it

There are multiple ways to fix this issue:

Code examples

Noncompliant code example

[HttpGet("foo")]
// Noncompliant: Annotate this method with ProducesResponseType containing the return type for succesful responses.
public IActionResult MagicNumber() => Ok(42);
[HttpGet("foo")]
// Noncompliant: Use the ProducesResponseType overload containing the return type for succesful responses.
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult MagicNumber() => Ok(42);

Compliant solution

[HttpGet("foo")]
[ProducesResponseType<int>(StatusCodes.Status200OK)]
public IActionResult MagicNumber() => Ok(42);
[HttpGet("foo")]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
public IActionResult MagicNumber() => Ok(42);

Resources

Documentation