dotnet / dotnet/aspnetcore

Analyzer Suggestion: Warn when returning incorrect type in ActionResult<T>

Open
#62,727 2 comments 5 reactions 0 assignees View on GitHub
analyzer area-mvc untriaged
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Analyzer Suggestion: Warn when returning incorrect type in `ActionResult`

#### Summary

When a controller action in ASP.NET Core declares a return type of `ActionResult`, the compiler currently allows returning an object of a different type via helper methods like `Ok(object)` or `NotFound(object)`, even if the returned type does not match `T`. This can lead to incorrect assumptions about the return type, misaligned Swagger documentation, or runtime serialization issues.

#### Example

```csharp
public ActionResult GetUser()
{
Product product = new Product();
return Ok(product); // ⚠️ Returns Product, not User
}
```

This compiles without warnings and executes at runtime, but semantically violates the expected contract that the response will be of type `User`. I am aware that this is not a bug but a feature because the `ActionResult` and the `Ok` are two different things that are independent of each other and the `Ok` method accepts parameter of type `object` so the generic type of `ActionResult` does not affect it's behaviour.

#### Motivation

Allowing a type mismatch between the declared `ActionResult` and the actual returned type can:

- Mislead API consumers about the actual response payload
- Cause inconsistencies in OpenAPI/Swagger documentation generation
- Introduce subtle runtime bugs or breaking changes during refactoring
- Reduce confidence in static analysis tools and type safety

#### Proposal

Introduce a Roslyn analyzer that:

- Reports a warning when the type passed to a result-producing method (`Ok(...)`, `NotFound(...)`, `Created(...)`, etc.) does not match or isn't assignable to the `T` in `ActionResult`
- Optionally offers a code fix to align the types (e.g., change the return type or cast the returned object)

This analyzer could live under a rule ID in the `ASP.NET.Core` or `CodeQuality` category.

#### Severity

`Warning`

#### Category

`Design` / `CodeQuality`

#### Related Information

- [`ActionResult` documentation](https://learn.microsoft.com/aspnet/core/web-api/?view=aspnetcore-8.0#actionresultt-type)
- [`ControllerBase.Ok(object)` documentation](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.ok)

#### Additional Context

This analyzer would align well with the .NET ecosystem’s emphasis on strong typing, predictable behavior, and robust tooling support. It helps developers catch issues early and maintain a more correct API contract.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.