Skip to content

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

Open
@BipinSubedi0608

Description

@BipinSubedi0608

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

Summary

When a controller action in ASP.NET Core declares a return type of ActionResult<T>, 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

public ActionResult<User> 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<T> 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<T>
  • 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

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesuntriaged

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions