Skip to content

OpenApi generate duplicate schemas #61408

Closed

Description

@oPreis-Systecs

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

In OpenApi (Version 9.0.4) schema json there are duplicate schemas if i use arrays.

Expected Behavior

Schemas should not duplicate.

Steps To Reproduce

Controller methods:

[HttpGet("new")]
[Produces("application/json")]
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable<EventDto>))]
public async Task<IActionResult> GetAllEventsWithImages()
{
    try
    {
        var events = await _eventLogic.GetAllNewEventsAsync();
        return Ok(events);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error while fetching new events.");
        return StatusCode((int)HttpStatusCode.InternalServerError, InternalServerErrorMessage);
    }
}

[HttpGet("{id:guid}")]
[Produces("application/json")]
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(EventDto))]
public async Task<IActionResult> GetEventById(Guid id)
{
    _logger.LogInformation("Fetching event with ID {EventId}", id);
    var eventDto = await _eventLogic.GetEventByIdAsync(id);

    if (eventDto == null)
    {
        _logger.LogWarning("Event with ID {EventId} not found", id);
        return NotFound($"Event with ID {id} not found");
    }

    return Ok(eventDto);
}

Dto:

public class EventDto
{
    public Guid Id { get; set; }
    public Guid? CreatorId { get; set; }
    public string? InputText { get; set; }
    public string? OutputText { get; set; }
    public EventStatus? Status { get; set; }

    public IEnumerable<ImageDto> Images { get; set; } = new List<ImageDto>();
    public IEnumerable<CollectionDto> Collections { get; set; } = new List<CollectionDto>();
}

Generated schema:

{
  "openapi": "3.0.1",
  "info": {
    "title": "Systecs.PortfolioManager.Server | v1",
    "version": "1.0.0"
  },
  "paths": {
    "/api/Event/new": {
      "get": {
        "tags": [
          "Event"
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/EventDto"
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/Event/{id}": {
      "get": {
        "tags": [
          "Event"
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EventDto2"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "CollectionDto": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "surname": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "date": {
            "type": "string",
            "format": "date-time"
          },
          "imageId": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "image": {
            "$ref": "#/components/schemas/ImageDto2"
          },
          "events": {
            "type": "array",
            "items": { }
          }
        }
      },
      "CollectionDto2": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "surname": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "date": {
            "type": "string",
            "format": "date-time"
          },
          "imageId": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "image": {
            "$ref": "#/components/schemas/ImageDto2"
          },
          "events": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/EventDto"
            }
          }
        }
      },
      "EventDto": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "creatorId": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "inputText": {
            "type": "string",
            "nullable": true
          },
          "outputText": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/NullableOfEventStatus"
          },
          "images": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ImageDto"
            }
          },
          "collections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CollectionDto"
            }
          }
        }
      },
      "EventDto2": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "creatorId": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "inputText": {
            "type": "string",
            "nullable": true
          },
          "outputText": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/NullableOfEventStatus"
          },
          "images": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ImageDto"
            }
          },
          "collections": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CollectionDto2"
            }
          }
        }
      },
      "ImageDto": {
        "required": [
          "imageData"
        ],
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "imageData": {
            "type": "string",
            "format": "byte"
          },
          "contentType": {
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/ImageType"
          }
        }
      },
      "ImageDto2": {
        "required": [
          "imageData"
        ],
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "imageData": {
            "type": "string",
            "format": "byte"
          },
          "contentType": {
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/ImageType"
          }
        },
        "nullable": true
      },
      "ImageType": {
        "type": "integer"
      },
      "NullableOfEventStatus": {
        "type": "integer",
        "nullable": true
      }
    }
  },
  "tags": [
    {
      "name": "Event"
    }
  ]
}

Exceptions (if any)

No response

.NET Version

9.0.200

Anything else?

No response

Activity

  1. ghost added
    needs-area-label
    on Apr 9, 2025
  2. added
    area-mvc
    and removed
    needs-area-label
    on Apr 9, 2025
  3. balukin commented on Apr 10, 2025

    @balukin

    Probably the same issue here. It was happening prior to 9.0.4, too. I'm using minimal API definitions (WithOpenApi() extension)

    public class Response
    {
        public Dictionary<string, SomeCustomType>? GroupedResults { get; set; } = new();
        public SomeCustomType? OverallResults { get; set; } 
    }

    Two schemas are generated #/components/schemas/SomeCustomType and #/components/schemas/SomeCustomType2.

    Temporary I can work around this with following configuration but it's too fragile to be a long term solution. Gets API clients to generate in dev loop with no errors, at least.

    services.AddOpenApi(options =>
    {
        options.AddSchemaTransformer((schema, context, cancellationToken) =>
        {
            if (schema.Properties is not null)
            {
                if (schema.Properties.TryGetValue("overallResults", out var overallResultsRef))
                {
                    overallResultsRef.Nullable = true; 
                    overallResultsRef.Reference = new OpenApiReference()
                    {
                        Id = "SomeCustomType", // forces SomeCustomType instead of SomeCustomType2
                        Type = ReferenceType.Schema,
                    };
                }
            }
    
            return Task.CompletedTask;
        });
    
    });

    Strangely enough, resulting JSON doesn't have nullable set to true on overallResults after this modification - I don't know why.

    "groupedResults": {
        "type": "object",
        "additionalProperties": {
            "$ref": "#/components/schemas/SomeCustomType"
        },
        "nullable": true
        },
        "overallResults": {
            // would be suffixed with `2` and cause entire new schema to generate without workaround
        "$ref": "#/components/schemas/SomeCustomType"
        },
  4. captainsafia commented on Jul 30, 2025

    @captainsafia
    Contributor

    Fixed in .NET 10.

    #:sdk Microsoft.NET.Sdk.Web
    #:property TargetFramework=net10.0
    #:property PublishAoT=false
    #:package Microsoft.AspNetCore.OpenApi@10.0.0-preview.7.*
    
    using Microsoft.AspNetCore.Mvc;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddOpenApi();
    
    var app = builder.Build();
    
    app.MapOpenApi();
    
    app.MapGet("/response", () =>
    {
        var response = new Response
        {
            GroupedResults = new Dictionary<string, SomeCustomType>
            {
                { "Group1", new SomeCustomType { /* initialize properties */ } },
                { "Group2", new SomeCustomType { /* initialize properties */ } }
            },
            OverallResults = new SomeCustomType { /* initialize properties */ }
        };
    
        return TypedResults.Ok(response);
    });
    
    app.MapGet("/event", () =>
    {
        var eventDto = new EventDto
        {
            Id = Guid.NewGuid(),
            CreatorId = Guid.NewGuid(),
            InputText = "Sample input",
            OutputText = "Sample output"
        };
    
        return TypedResults.Ok(eventDto);
    });
    
    app.MapGet("/events", () =>
    {
        var events = new List<EventDto>
        {
            new EventDto
            {
                Id = Guid.NewGuid(),
                CreatorId = Guid.NewGuid(),
                InputText = "Sample input 1",
                OutputText = "Sample output 1",
            },
            new EventDto
            {
                Id = Guid.NewGuid(),
                CreatorId = Guid.NewGuid(),
                InputText = "Sample input 2",
                OutputText = "Sample output 2",
            }
        };
    
        return TypedResults.Ok(events);
    });
    
    
    
    app.Run();
    
    public class Response
    {
        public Dictionary<string, SomeCustomType>? GroupedResults { get; set; } = new();
        public SomeCustomType? OverallResults { get; set; }
    }
    
    public class SomeCustomType
    {
        // Define properties for SomeCustomType
        public string Property1 { get; set; }
        public int Property2 { get; set; }
    }
    
    public class EventDto
    {
        public Guid Id { get; set; }
        public Guid? CreatorId { get; set; }
        public string? InputText { get; set; }
        public string? OutputText { get; set; }
    }
    {
      "openapi": "3.1.1",
      "info": {
        "title": "61408 | v1",
        "version": "1.0.0"
      },
      "servers": [
        {
          "url": "http://localhost:5000/"
        }
      ],
      "paths": {
        "/response": {
          "get": {
            "tags": [
              "61408"
            ],
            "responses": {
              "200": {
                "description": "OK",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/Response"
                    }
                  }
                }
              }
            }
          }
        },
        "/event": {
          "get": {
            "tags": [
              "61408"
            ],
            "responses": {
              "200": {
                "description": "OK",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/EventDto"
                    }
                  }
                }
              }
            }
          }
        },
        "/events": {
          "get": {
            "tags": [
              "61408"
            ],
            "responses": {
              "200": {
                "description": "OK",
                "content": {
                  "application/json": {
                    "schema": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/EventDto"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "components": {
        "schemas": {
          "EventDto": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "creatorId": {
                "type": [
                  "null",
                  "string"
                ],
                "format": "uuid"
              },
              "inputText": {
                "type": [
                  "null",
                  "string"
                ]
              },
              "outputText": {
                "type": [
                  "null",
                  "string"
                ]
              }
            }
          },
          "Response": {
            "type": "object",
            "properties": {
              "groupedResults": {
                "type": [
                  "null",
                  "object"
                ],
                "additionalProperties": {
                  "$ref": "#/components/schemas/SomeCustomType"
                }
              },
              "overallResults": {
                "$ref": "#/components/schemas/SomeCustomType"
              }
            }
          },
          "SomeCustomType": {
            "type": [
              "null",
              "object"
            ],
            "properties": {
              "property1": {
                "type": "string"
              },
              "property2": {
                "pattern": "^-?(?:0|[1-9]\\d*)$",
                "type": [
                  "integer",
                  "string"
                ],
                "format": "int32"
              }
            }
          }
        }
      },
      "tags": [
        {
          "name": "61408"
        }
      ]
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcfeature-openapi

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions