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.
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:
[ProducesResponseType] attribute containing the return type, either at controller or action level. [SwaggerResponse] attribute containing the return type, either at controller or action level. [ApiController] attribute.
There are multiple ways to fix this issue:
[ProducesResponseType]
containing the return type. [IActionResult] or [IResult]. [IActionResult] or [IResult].
[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);
[HttpGet("foo")]
[ProducesResponseType<int>(StatusCodes.Status200OK)]
public IActionResult MagicNumber() => Ok(42);
[HttpGet("foo")]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
public IActionResult MagicNumber() => Ok(42);