aspnetcore: Microsoft.AspNetCore.OpenApi fails to generate document when using polymorphic types
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
Using polymorphic types and returning both the base class and derived class in separate controller actions causes OpenApi document generation to fail.
Document generation succeeds if you disable/remove public ComponentDto GetComponent() action in the provided example repository.
Also it seems like something is wrong with the generated document (when the exception causing controller action is removed). At most I would expect two model schemas to be generated
ComponentDtoComponentDtoSectionDto- does Microsoft.AspNetCore.OpenApi support custom names? I don’t like the auto-generated one.
but it also generates a weird looking SectionDto schema which seems like a weird mix of ComponentDto & SectionDto
Expected Behavior
OpenApi document generation should not fail and should generate correct schemas when using polymorphic types.
Steps To Reproduce
https://github.com/keenjus/OpenApiStuff/tree/7d736b83d4ddf5b4208580b9d265d690f082d7b4
Launch the project and navigate to http://localhost:5052/openapi/v1.json. Should fail with "ArgumentException: An item with the same key has already been added. Key: ComponentDtoSectionDto "
Exceptions (if any)
ArgumentException: An item with the same key has already been added. Key: ComponentDtoSectionDto
System.Collections.Generic.Dictionary<TKey, TValue>.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
System.Collections.Generic.Dictionary<TKey, TValue>.Add(TKey key, TValue value)
Microsoft.AspNetCore.OpenApi.OpenApiSchemaReferenceTransformer.TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.ApplyTransformersAsync(OpenApiDocument document, IServiceProvider scopedServiceProvider, CancellationToken cancellationToken)
Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOpenApiDocumentAsync(IServiceProvider scopedServiceProvider, CancellationToken cancellationToken)
Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOpenApiDocumentAsync(IServiceProvider scopedServiceProvider, CancellationToken cancellationToken)
Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions+<>c__DisplayClass0_0+<<MapOpenApi>b__0>d.MoveNext()
Microsoft.AspNetCore.Http.Generated.<GeneratedRouteBuilderExtensions_g>F56B68D2B55B5B7B373BA2E4796D897848BC0F04A969B1AF6260183E8B9E0BAF2__GeneratedRouteBuilderExtensionsCore+<>c__DisplayClass2_0+<<MapGet0>g__RequestHandler|5>d.MoveNext()
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
.NET Version
9.0.100-rc.1.24452.12
Anything else?
Microsoft.AspNetCore.OpenApi 9.0.0-rtm.24501.7
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 17
- Comments: 20 (3 by maintainers)
I’m also having the same problem with Microsoft.AspNetCore.OpenApi 9.0.3
Any updates on this? I have run into this issue in two separate projects, and it’s preventing us from moving to
OpenAIOpenApi. The suggestions from @marinasundstrom does get it to generate a valid OpenApi document when using an “add random stuff to the model names” strategy, but that is not a feasible fix.I’m also getting the same
ArgumentException: An item with the same key has already been added., which unfortunately blocks me from updating my project to .NET 9 at this point.still throw ‘An item with the same key has already been added’ exception with polymorphic types in 9.0.4
Still a problem for me on 9.0.5
Can also confirm that the ‘An item with the same key has already been added’ exception with polymorphic types in 9.0.4 no longer happens 🚀
I think the AddOpenAPI might have just started ignoring the default JsonOptions, so even the bits that used to generate now don’t.
.Configure<JsonOptions>(o => { o.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; o.SerializerOptions.MaxDepth = 500; });
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.Text.Json.JsonReaderException: The maximum configured depth of 64 has been exceeded. Cannot read next JSON object. LineNumber: 0 | BytePositionInLine: 20767. at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan
1 bytes) at System.Text.Json.Utf8JsonReader.StartObject() at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker) at System.Text.Json.Utf8JsonReader.ReadSingleSegment() at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.JsonDocument.Parse(ReadOnlySpan1 utf8JsonSpan, JsonReaderOptions readerOptions, MetadataDb& database, StackRowStack& stack) at System.Text.Json.JsonDocument.ParseUnrented(ReadOnlyMemory1 utf8Json, JsonReaderOptions readerOptions, JsonTokenType tokenType) at System.Text.Json.JsonDocument.ParseValue(ReadOnlyMemory1 json, JsonDocumentOptions options) at System.Text.Json.Nodes.JsonNode.Parse(String json, Nullable`1 nodeOptions, JsonDocumentOptions documentOptions) at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveRelativeReferences(JsonNode node, JsonNode rootNode) at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveRelativeReferences(JsonNode node, JsonNode rootNode)Still a problem in 9.0.1!
@captainsafia
I dug into the source code and found that the actual name that will be used as reference id, or key, in the completed schema is stored under Annotations with the key
x-schema-id.I can modify that like so:
The type
OpenApiConstantsis not public. Otherwise, I would have usedOpenApiConstants.SchemaId.I initially wondered why the
doc.Component.Schemawasn’t set in the Document Transformer. But found out that the last step of creating the document is this special transformerOpenApiSchemaReferenceTransformerthat runs last.Anyway, I’m starting to understand how this works. Not that different from any compiler having to keep track of references to types, members, and variables etc. 🙂