aspnetcore: [Open API] Nullability set on component schema level and not operation. Causing multiple component schemas being generated.

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Deal-breaker for migration. I discovered this while porting my API from using NSwag.

One component schema per type, not distinct schemas based om nullability. And I think this is a part of a bigger story about dealing with nullability.

I think this also affects Minimal APIs.

In this particular case, it seems like nullability is set on a component schema-level and not the schema on on parameter and response-level

This happens because of the action (Test) with return type TestDto regardless of whether it is nullable or not. So no concern for explicit nullability either.

Following is for OpenAPI 3.

Consider this controller:

[ApiController]
[Route(“[controller]")]
public class StatisticsController : ControllerBase
{

    // TestDto corresponds to component schema "TestDto2" with nullable: true

    [HttpGet("Test")]
    public TestDto Test()
    {
        return default!;
    }

/*
    // Not relevant
    [HttpGet("Test2")]
    public TestDto? Test2()
    {
        return default!;
    }
*/

    // TestDto corresponds to component schema "TestDto" (with nullable: false)

    [HttpGet("Test3")]
    public KeyValuePair<int, TestDto> Test3()
    {
        return default!;
    }
}

Instead of one TestDto schema, it results in two distinct schemas TestDto and TestDto2 where one is nullable.

The response on the operation should be nullable at an operation-level, not at component schema level:

components:
  schemas:
    TestDto:
      required:
        - x
      type: object
      properties:
        x:
          type: string
    TestDto2:
      required:
        - x
      type: object
      properties:
        x:
          type: string
      nullable: true <—- THIS IS WHY THE TYPE HAS TWO SCHEMAS:

With the operation being tis:

paths:
  /Statistics/Test2:
    get:
      tags:
        - Statistics
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                $ref: '#/components/schemas/TestDto2’
            application/json:
              schema:
                $ref: '#/components/schemas/TestDto2’
            text/json:
              schema:
                $ref: '#/components/schemas/TestDto2’

Expected Behavior

I would expect this operation with the shared component schema, and the nullability set on the operation:

paths:
  /Statistics/Test2:
    get:
      tags:
        - Statistics
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/TestDto'
                nullable: true
components:
  schemas:
    TestDto:
      required:
        - x
      type: object
      properties:
        x:
          type: string

Meaning the use of ”allOf” and ”nullable: true” on the response.

This allows for maximal re-use of DTOs. Not having two otherwise identical schemas that are different in nullability.

Steps To Reproduce

var builder = WebApplication.CreateBuilder();

builder.Services.AddControllers();

builder.Services.AddOpenApi();

var app = builder.Build();

app.MapControllers();

app.MapOpenApi();

app.Run();

Exceptions (if any)

No response

.NET Version

9.0.100-rc.2.24474.11

Anything else?

The bigger story would be to write a transformer that deals with nullability for parameters and responses.

I’m on my way prototyping for my own project.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 3
  • Comments: 20 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I should have mentioned … there is an issue for adding support for OpenAPI v3.1.

https://github.com/dotnet/aspnetcore/issues/58619

Feel free to put a thumb’s up reaction there if this is important to you.

I believe its still an issue with nullable

If you return this Person class

public class Person
{
    public string Name { get; set; } = string.Empty;
    public Address MyAddress { get; set; } = new();
    public Address? MyAltAddress { get; set; }
}
public class Address
{
    public string Street { get; set; } = string.Empty;
    public int Number { get; set; }
}```

the resulting schema is
```json
"components": {
    "schemas": {
      "Address": {
        "type": "object",
        "properties": {
          "street": {
            "type": "string"
          },
          "number": {
            "type": "integer",
            "format": "int32"
          }
        }
      },
      "Address2": {
        "type": "object",
        "properties": {
          "street": {
            "type": "string"
          },
          "number": {
            "type": "integer",
            "format": "int32"
          }
        },
        "nullable": true
      },
      "Person": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "myAddress": {
            "$ref": "#/components/schemas/Address"
          },
          "myAltAddress": {
            "$ref": "#/components/schemas/Address2"
          }
        }
      }
    }
  }

But you want the schema as

"components": {
    "schemas": {
      "Address": {
        "type": "object",
        "properties": {
          "street": {
            "type": "string"
          },
          "number": {
            "type": "integer",
            "format": "int32"
          }
        }
      },
      "Person": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "myAddress": {
            "$ref": "#/components/schemas/Address"
          },
          "myAltAddress": {
            "$ref": "#/components/schemas/Address",
            "nullable": true
          }
        }
      }
    }
  }

You dont want the new type Address2, you want the reference to be nullable

Any update on this?

The way it currently works makes it impossible to have a shared DTO library be used alongside the OpenAPI spec for interface generation (without manual modifications after the fact), because the names won’t be the same as the classes in the library because of the numbers it appends.

It may technically be “working by design” but that’s a useless excuse if that design is blocking usage.

@Chrille79 I can understand why you’d prefer not to have Address2, just so that it is nullable. But I think it does accurately describe the class from a JSON schema perspective. Further, I don’t think there are any good alternatives.

The solution you propose – putting nullable: true next to the “$ref” – isn’t allowed as JSON Schema prohibits sibling properties of $ref.

Another approach – discussed above – is to use “allOf” like this:

          "myAltAddress": {
            "allOf": [{
              "$ref": "#/components/schemas/Address"
            }],
            "nullable": true
          }

which doesn’t work either because Address specifies type: object and not nullable: true, which does not allow a “null” value and thus does not satisfy the “allOf”.

Thanks for the full repro. This is very helpful and I believes a few things we observed from our side.

  • When the action method has a return type of TestDto or TestDto?, the schema in the response is not marked as “nullable: true”. This is accurate because of a quirk in the way Controller-based apps work: a “null” response is converted to a 204 No Content response. Now there is a problem in that the 204 response is not shown in the generated OpenApi, but the definition of the 200 response is correct.

  • When the action method accepts a TestDto?, as is the case for T2 in your project, the request body is defined as nullable and this is also correct, because sending “null” in the request body will set the body parameter to null.

Regarding generating a single schema for TestDto and using allOf to set nullable on or off, this is an interesting approach and we will take this under consideration.