Skip to content

OpenAPI does not generate reference to self when returning arrays in controllers #61424

@iskandersierra

Description

@iskandersierra

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When a controller's action returns a collection type like List<Item> or a class that contains such collection, and Item contains a property of type List<Item>, the OpenAPI spec generator generates an untyped array for the self-referencing property.

Issue #61408 seems to be related but with a more complex setup

Expected Behavior

I expected that the OpenAPI spec generator generated a typed array where the items had a "$ref" to the same model.

Steps To Reproduce

See repro at: https://github.com/iskandersierra/OpenApiSelfReferenceRepro

The models are the following:

public class Level1
{
    public IReadOnlyList<Level1> Level1s { get; set; } = [];
}

And the Controller code is:

[ApiController]
[Route("[controller]")]
public class LevelController : ControllerBase
{
    [HttpGet(Name = "GetLevels")]
    public IReadOnlyList<Level1> GetLevels()
    {
        return new();
    }
}

However the schemas generated by OpenAPI are not correct:

{
    "Level1": {
        "type": "object",
        "properties": {
            "level1s": {
                "type": "array",
                "items": { }
            }
        }
    }
}

And it should be:

{
    "Level1": {
        "type": "object",
        "properties": {
            "level1s": {
                "type": "array",
                "items": { "$ref": "#/components/schemas/Level1" }
            }
        }
    }
}

Some facts:

  • It doesn't matter which type of collection we return in the controller, the issue is always the same.
  • If the controller returns Level1 instead of IReadOnlyList<Level1>, the schema is generated correctly.`
  • If there is a second action returning the Level1 type, the schema gets the Level1 duplicated as Level12, one gets generated correctly and the other one incorrectly, depending on the order of the actions in the controller.

Exceptions (if any)

No exception is detected, just the wrong schema specification.

.NET Version

9.0.203

Anything else?

Project 'OpenApiSelfReferenceRepro' has the following package references
   [net9.0]: 
   Top-level Package                   Requested   Resolved
   > Microsoft.AspNetCore.OpenApi      9.0.4       9.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions