aspnetcore: .NET 9 OpenAPI produces lots of duplicate schemas for the same object

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

A very simple circular/recursive data model produces a ton of duplicate schema definitions like Object, Object2, Object3, Object4, and so on.

Expected Behavior

Each class in C# is represented in the OpenAPI schema only once, as was the case with Swashbuckle.

Steps To Reproduce

  • Brand new .NET 9 Web API from template, with OpenAPI enabled.
  • Replace WeatherForecastController:
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet("GetParent")]
        public ParentObject GetParent() => new();

        [HttpGet("GetChild")]
        public ChildObject GetChild() => new();
    }

    public class ParentObject
    {
        public int Id { get; set; }
        public List<ChildObject> Children { get; set; } = [];
    }

    public class ChildObject
    {
        public int Id { get; set; }
        public ParentObject? Parent { get; set; }
    }
  • Launch app
  • Look at /openapi/v1.json
  • Observe ChildObject2, ParentObject2, ParentObject3, which shouldn’t exist.
{
  "openapi": "3.0.1",
  "info": {
    "title": "aspnet9api | v1",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://localhost:7217"
    },
    {
      "url": "http://localhost:5067"
    }
  ],
  "paths": {
    "/WeatherForecast/GetParent": {
      "get": {
        "tags": [
          "WeatherForecast"
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "text/plain": {
                "schema": {
                  "$ref": "#/components/schemas/ParentObject"
                }
              },
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ParentObject"
                }
              },
              "text/json": {
                "schema": {
                  "$ref": "#/components/schemas/ParentObject"
                }
              }
            }
          }
        }
      }
    },
    "/WeatherForecast/GetChild": {
      "get": {
        "tags": [
          "WeatherForecast"
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "text/plain": {
                "schema": {
                  "$ref": "#/components/schemas/ChildObject2"
                }
              },
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChildObject2"
                }
              },
              "text/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChildObject2"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "ChildObject": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "parent": {
            "$ref": "#/components/schemas/ParentObject2"
          }
        }
      },
      "ChildObject2": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "parent": {
            "$ref": "#/components/schemas/ParentObject3"
          }
        }
      },
      "ParentObject": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "children": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChildObject"
            }
          }
        }
      },
      "ParentObject2": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "children": {
            "$ref": "#/components/schemas/#/properties/children"
          }
        },
        "nullable": true
      },
      "ParentObject3": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "children": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChildObject"
            }
          }
        },
        "nullable": true
      }
    }
  },
  "tags": [
    {
      "name": "WeatherForecast"
    }
  ]
}

.NET Version

9.0.100

Anything else?

In my real-world application, the worst offending model has been duplicated 39 times: Image

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 36
  • Comments: 49 (11 by maintainers)

Commits related to this issue

Most upvoted comments

@captainsafia Sorry for the ping, but I know you worked a lot on the OpenAPI stuff. Wasn’t sure if you’d seen this yet - it essentially makes the entire feature completely unusable beyond the most trivial applications.

Hi everyone! First of all, thank you for your patience here. Most important info: this bug has been fixed in .NET 10 and back-ported to .NET 9. You’ll find it in the next servicing release for .NET 9.

Why did this bug happen? The crux of the issue comes from the incompatibility between schemas generated by System.Text.Json, which comply strictly with the JSON Schema specification, and those expected by the OpenAPI.NET package which are a superset of JSON Schema. STJ uses relative references to capture recursive or duplicate type references. OpenAPI.NET does not recognize these as equivalent which results in duplicate schemas.

In .NET 9, we fix this by introducing logic to our custom comparers to treat relative references as equivalent to any generated type.

In .NET 10, we’re upgrading to the new version of the OpenAPI.NET package which adds in built-in support for being able to resolve these relative references and detect “loop-backs” in the schema model.

I’ll keep this issue open until the next .NET 9 servicing release ships. In the meantime, happy to answer any questions about the issue.

I have now tried version 9.0.4. This fixes a reference in my json, but unfortunately there are still duplicated schemas when arrays are used.

I also encountered this problem in eShop. In that case and maybe others it seems to come down to a difference in the “nullable” attribute in two uses of the schema. When the schema is for a property, it is marked as “nullable: true” because System.Text.Json accepts the value “null” and treats it as “not provided”. When the schema is for the “items” of an array, “null” is not allowed so the schema defaults to “nullable: false”.

I found that I could fix the duplicate schema problem in eShop with a schema transformer that removes nullable: true from any properties that are “optional” (not listed in the “required” keyword of the schema). The transformer is pretty small so I’ll just include the code here in case anyone else wants to try it:

    options.AddSchemaTransformer((schema, context, cancellationToken) =>
    {
        if (schema.Properties is not null)
        {
            foreach (var property in schema.Properties)
            {
                if (schema.Required?.Contains(property.Key) != true)
                {
                    property.Value.Nullable = false;
                }
            }
        }
        return Task.CompletedTask;
    });

Still seeing the same issue. Number of duplications have reduced, but still there are duplicates.

Sample: https://github.com/jaliyaudagedara/repro-aspnetcore-openapi-dup-schemas

With 9.0.0 Image

With 9.0.2 Image

I do not use “nullable types” feature in any of my projects. Never have.

@vitasystems Based on the screenshot you shared, it looks like what you’re running into is a variant of https://github.com/dotnet/aspnetcore/issues/60339. If you’re able to share more repro details over there, that might help affirm if my hunch is correct.

Even the configuration of the Json options does not work still… It only takes into account Minimal API which I would bet money it is not what most people are using… Not even for greenfield dev.

Yes, this is unfortunately a known issue. MVC has long has its own set of JSON options that are optimized for MVC-specific binding APIs. We introduced ConfigureHttpJsonOptions in .NET 7 to provide a way for JSON options to be configured for components outside of minimal APIs. This includes the OpenAPI package, but other features as well like the ProblemDetails service and the exception middleware. Simply put, we need a way to customize JSON behavior throughout ASP.NET Core and relying on MVC’s JSON options type means you have to bring in higher-level MVC assemblies into lower-level APIs which is a no go.

I dont mean to beat a dead horse here. But i think the whole “remove swagger from templates” and “we have a new official open api generator” thing was a bit hasty. This feature is like super important I would even say it is core to any API in modern times. The fact that this has never worked on any version of NET 9 feels like it needs more testing and maybe go back to alpha.

I totally understand your frustration here. Nobody likes bugs and it’s disappointing when things don’t behave the way they should. However, that shouldn’t be taken as a reflection of a feature not being important. Having OpenAPI support built-in to the framework has helped generate some activity in this space, like support for JSON Schema in STJ and OpenAPI 3.1 support and .NET-centric packages for UIs like Scalar, that ultimately accrues to a net benefit for the ecosystem as a whole.

Issue #58915 has been closed in favor of this one, but it describes a different problem where the references are invalid in the schema. That issue also remains unresolved in version 9.0.2

I get the same problem. Specifically when multiple collections of a schema are present:

public class TestOpenApiResult
{
    public List<SingleItemDataResult> FirstListOfItems { get; init; }
    public SingleItemDataResult MainItem { get; init; }
    public SingleItemDataResult SecondMainItem { get; init; }
    public List<SingleItemDataResult> SecondListOfItems {get; init;}
    public SingleItemDataResult[] FirstArrayOfItems {get; init;}
}

Results in the following invalid schema:

"TestOpenApiResult": {
        "type": "object",
        "properties": {
          "firstListOfItems": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SingleItemDataResult"
            },
            "nullable": true
          },
          "mainItem": {
            "$ref": "#/components/schemas/SingleItemDataResult2"
          },
          "secondMainItem": {
            "$ref": "#/components/schemas/SingleItemDataResult2"
          },
          "secondListOfItems": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/#/items/properties/firstListOfItems/items"
            },
            "nullable": true
          },
          "firstArrayOfItems": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/#/items/properties/firstListOfItems/items"
            },
            "nullable": true
          }
        },
        "nullable": true
      }

This output was generated using 9.0.2, and is completely unchanged from 9.0.1

We can prevent the duplicate with a schema transformer to force all instances of SingleItemDataResult to be nullable, but the invalid entries are proving to be a blocking issue with client generation.

@JustArchi I wrote this powershell script to rewrite parts of the generated JSON spec:

FixSpec.ps1
param (
	[Parameter(Mandatory = $true)]
	[string]$SpecFile
)

function Replace-ObsoleteRefs {
	param (
		[PSCustomObject]$Object,
		[hashtable]$ModelMap
	)
	foreach ($property in $Object.PSObject.Properties) {
		if ($property.Value -is [PSCustomObject]) {
			# Recursively handle nested objects
			Replace-ObsoleteRefs -Object $property.Value -ModelMap $ModelMap
		} elseif ($property.Value -is [System.Collections.IEnumerable] -and -not ($property.Value -is [string])) {
			# Recursively handle arrays
			foreach ($item in $property.Value) {
				if ($item -is [PSCustomObject]) {
					Replace-ObsoleteRefs -Object $item -ModelMap $ModelMap
				}
			}
		} elseif ($property.Name -eq '$ref') {
			# Update $ref if it matches a model in the map
			$refValue = $property.Value -replace '.*/'
			if ($ModelMap.ContainsKey($refValue)) {
				$property.Value = $property.Value -replace $refValue, $ModelMap[$refValue]
			}
		}
	}
}

function Find-KeyCaseInsensitive {
	param(
		[PSCustomObject]$obj,
		[string]$key
	)
	$obj.PSObject.Properties | Where-Object { $_.Name -ieq $key } | Select-Object -First 1
}

# Recursive function to fix invalid $ref entries
function Fix-InvalidNestedRefs {
	param (
		[PSCustomObject]$root,
		[PSCustomObject]$node,
		[PSCustomObject]$parent
	)

	foreach ($key in $node.PSObject.Properties.Name) {
		$value = $node.$key

		if ($key -eq '$ref' -and $value -match '^#/components/schemas/#/.*') {
			# Split the ref path by '/' and drop everything before the last 'properties'
			$refParts = $value -split '/'
			$lastPropertiesIndex = [Array]::LastIndexOf($refParts, 'properties')

			if ($lastPropertiesIndex -gt 0) {
				# Extract the part before the last 'properties' to get the target schema
				$targetParts = $refParts[($lastPropertiesIndex - 1)..($refParts.Length - 1)]

				# Traverse the schema using the base path and relevant parts
				$targetSchema = $root.components.schemas

				# Traverse to the target schema based on the basePath
				foreach ($part in $targetParts) {
					$targetProperty = Find-KeyCaseInsensitive -obj $targetSchema -key $part
					if ($targetProperty) {
						$targetSchema = $targetProperty.Value

						if ($targetProperty.Name -eq '$ref') {
							break
						}
					}
					else
					{
						throw "Could not find '$part' of target schema '" + ($targetParts -join '/') + "' in available keys $( $targetSchema.PSObject.Properties.Name -join ', ' )"
					}
				}

				# If path is valid, replace the ref with the found schema
				$node.$key = $targetSchema.'$ref'
			}
		} elseif ($value -is [PSCustomObject]) {
			Fix-InvalidNestedRefs -root $root -node $value -parent $node
		} elseif ($value -is [System.Collections.IEnumerable]) {
			foreach ($item in $value) {
				if ($item -is [PSCustomObject]) {
					Fix-InvalidNestedRefs -root $root -node $item -parent $node
				}
			}
		}
	}
}

try {
	# Load the OpenAPI spec
	$spec = Get-Content -Raw -Path $SpecFile | ConvertFrom-Json

	# Check if components.schemas exists
	if (-not $spec.components -or -not $spec.components.schemas) {
		throw "The input file does not contain a valid 'components.schemas' section."
	}
	$schemas = $spec.components.schemas

	# Validate that schemas is a PSCustomObject
	if (-not ($schemas -is [PSCustomObject])) {
		throw "'components.schemas' is not a valid PSCustomObject. Please verify the input JSON structure."
	}

	$uniqueModels = @{}
	$modelMap = @{}

	# Detect and map duplicate models
	foreach ($property in $schemas.PSObject.Properties) {
		$key = $property.Name
		$baseName = $key -replace '\d+$'
		if (-not $uniqueModels.ContainsKey($baseName)) {
			$uniqueModels[$baseName] = $key
		} else {
			if ($schemas.$($uniqueModels[$baseName]).GetHashCode() -eq $schemas.$key.GetHashCode()) {
				$modelMap[$key] = $uniqueModels[$baseName]
			}
		}
	}

	# Update all $ref values recursively
	Replace-ObsoleteRefs -Object $spec -ModelMap $modelMap

	# Remove duplicate models
	foreach ($key in $modelMap.Keys) {
		$schemas.PSObject.Properties.Remove($key)
	}

	# Fix invalid $ref entries
	Fix-InvalidNestedRefs -root $spec -node $spec -parent $null

	# Save the modified spec
	$spec | ConvertTo-Json -Depth 100 | Set-Content -Path $SpecFile
	Write-Host "Successfully updated the OpenAPI spec and saved to $SpecFile."
} catch {
	Write-Error "Error: $_"
}

You can weave it into your MSBuild project using this target:

	<Target Name="FixSpec" DependsOnTargets="GenerateOpenApiDocuments" AfterTargets="GenerateOpenApiDocuments" BeforeTargets="Build">
		<Message Importance="high" Text="Fixing OpenAPI spec"/>
		<Exec
			Command="pwsh -ExecutionPolicy Unrestricted -NoProfile -File $(MSBuildThisFileDirectory)FixSpec.ps1 -SpecFile $(OpenApiDocumentsDirectory)\$(MSBuildProjectName).json"
			LogStandardErrorAsError="true"
			ContinueOnError="False"
		/>
	</Target>

Patches are released on the second Tuesday of a month to align with Microsoft’s Update Tuesday, so the earliest would be 11th February.

OK! Thank you for all the follow-up feedback here. I’ve investigated the reports provided and it seems like all the reports are variants of https://github.com/dotnet/aspnetcore/issues/60339.

I’ve verified that the bug does not repro in .NET 10, which uses the new version of Microsoft.OpenApi that has built-in support for JSON schema references.

I’ve got a PR out to release/9.0 so that this can be included in the next servicing release that we can snap to.

I’ll close this issue out in favor of tracking this new bug instance on the aforementioned issue.

Hello everyone! Thanks for trying out the 9.0.2 release that was shipped yesterday.

Thanks to @jaliyaudagedara and @haverjes for sharing repros here. It appears that the issues you are running into deal with the same kinds of object types. I’ve pulled out the bug report for this into https://github.com/dotnet/aspnetcore/issues/60339.

Issue https://github.com/dotnet/aspnetcore/issues/58915 has been closed in favor of this one, but it describes a different problem where the references are invalid in the schema. That issue also remains unresolved in version 9.0.2

Upon further inspection, it appears that this is actually the case because the schemas that you are representing are distinct. One is a nullable type and the other is a non-nullable type.

@captainsafia I’m still seeing the issue. Specifically on a model that references an enum value on two different properties I’m seeing the enum repeated twice in the schema section of the JSON document.

Similar to the above, is there a chance that the nullability differs between the two properties you’re comparing here? If so, the schemas are not actually duplicates since they differ in nullability. In this case, you may want to consider using the CreateSchemaId option to modify the name used for non-nullable vs. nullable enums in your project.

Issue #58915 has been closed in favor of this one, but it describes a different problem where the references are invalid in the schema. That issue also remains unresolved in version 9.0.2

@captainsafia I’m still seeing the issue. Specifically on a model that references an enum value on two different properties I’m seeing the enum repeated twice in the schema section of the JSON document.

Has anyone come up with a viable workaround here? I was planning on addressing it with a DocumentTransformer but unfortunately the Document transformer, while it is called after my schema transformers, does not seem to have access to the schema objects.

document.Components.Schemas

remains empty when the DocumentTranformer.TransformAsync is invoked.