Skip to content

Set additionalProperties when [JsonExtensionData] is present #56767

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/OpenApi/sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Frozen;
using System.Collections.Immutable;
using System.ComponentModel;
using Microsoft.AspNetCore.Http.HttpResults;
Expand Down Expand Up @@ -111,6 +110,7 @@
schemas.MapPost("/shape", (Shape shape) => { });
schemas.MapPost("/weatherforecastbase", (WeatherForecastBase forecast) => { });
schemas.MapPost("/person", (Person person) => { });
schemas.MapPost("/problem-details", () => { }).ProducesProblem(statusCode: 500);

app.MapControllers();

Expand Down
11 changes: 11 additions & 0 deletions src/OpenApi/src/Services/Schemas/OpenApiSchemaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ internal sealed class OpenApiSchemaService(
{
schema = new JsonObject();
}
// STJ operates under the assumption that JSON Schema makes around `additionalProperties` being
// true by default for all schemas. OpenAPI v3 takes a different interpretation and assumes that
// `additionalProperties` is false by default. We override the default behavior assumed by STJ to
// match the OpenAPI v3 interpretation here by checking to see if any properties on a type map to
// extension data and explicitly setting the `additionalProperties` keyword to an empty object.
// Since `[ExtensionData]` can only be applied on dictionaries with `object` or `JsonElement` values
// there is no need to encode a concrete schema for thm and the catch-all empty schema is sufficient.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// there is no need to encode a concrete schema for thm and the catch-all empty schema is sufficient.
// there is no need to encode a concrete schema for them and the catch-all empty schema is sufficient.

if (context.TypeInfo.Properties.Any(jsonPropertyInfo => jsonPropertyInfo.IsExtensionData))
{
schema[OpenApiSchemaKeywords.AdditionalPropertiesKeyword] = new JsonObject();
}
var createSchemaReferenceId = optionsMonitor.Get(documentName).CreateSchemaReferenceId;
schema.ApplyPrimitiveTypesAndFormats(context, createSchemaReferenceId);
schema.ApplySchemaReferenceId(context, createSchemaReferenceId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,25 @@
}
}
}
},
"/schemas-by-ref/problem-details": {
"post": {
"tags": [
"Sample"
],
"responses": {
"500": {
"description": "Internal Server Error",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
}
}
}
},
"components": {
Expand Down Expand Up @@ -440,6 +459,33 @@
}
}
},
"ProblemDetails": {
"type": "object",
"properties": {
"type": {
"type": "string",
"nullable": true
},
"title": {
"type": "string",
"nullable": true
},
"status": {
"type": "integer",
"format": "int32",
"nullable": true
},
"detail": {
"type": "string",
"nullable": true
},
"instance": {
"type": "string",
"nullable": true
}
},
"additionalProperties": { }
},
"Product": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;

public partial class OpenApiSchemaServiceTests : OpenApiDocumentServiceTestBase
{
[Fact]
public async Task SetsAdditionalPropertiesOnBuiltInTypeWithExtensionData()
{
var builder = CreateBuilder();

builder.MapPost("/", () => new ProblemDetails());

await VerifyOpenApiDocument(builder, document =>
{
var schema = document.Components.Schemas["ProblemDetails"];
Assert.NotNull(schema.AdditionalProperties);
Assert.Null(schema.AdditionalProperties.Type);
});
}

[Fact]
public async Task SetAdditionalPropertiesOnDefinedTypeWithExtensionData()
{
var builder = CreateBuilder();

builder.MapPost("/", () => new MyExtensionDataType("test"));

await VerifyOpenApiDocument(builder, document =>
{
var schema = document.Components.Schemas["MyExtensionDataType"];
Assert.NotNull(schema.AdditionalProperties);
Assert.Null(schema.AdditionalProperties.Type);
});
}

[Fact]
public async Task SetsAdditionalPropertiesOnDictionaryTypesWithSchema()
{
var builder = CreateBuilder();

builder.MapPost("/", (Dictionary<string, Guid> data) => { });

await VerifyOpenApiDocument(builder, document =>
{
var operation = document.Paths["/"].Operations[OperationType.Post];
var schema = operation.RequestBody.Content["application/json"].Schema.GetEffective(document);
Assert.NotNull(schema.AdditionalProperties);
Assert.Equal("string", schema.AdditionalProperties.Type);
Assert.Equal("uuid", schema.AdditionalProperties.Format);
});
}

private class MyExtensionDataType(string name)
{
public string Name => name;

[JsonExtensionData]
public IDictionary<string, object> ExtensionData { get; set; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth having a test for the JsonElement case also mentioned in the description? Possibly also a class that derives from something with the base having the extension property?

}
}
Loading