Skip to content

Model nullable types using allOf in JSON schema #63029

@captainsafia

Description

@captainsafia

This is a meta issue to track a bunch of the bug reports are how culpability is modeled in the OpenAPI document.

Prior to OpenAPI 3.1, nullability in schemas was modeled using the nullable: true property in the schema. This presented a challenge for scenarios where the same type appeared as nullable in on scenario and non-nullable in another. For example:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/nullable", (Person? person) =>
{
    if (person is null)
    {
        return Results.BadRequest("Person is null");
    }

    return Results.Ok($"Received: {person.Name}, {person.Age}");
});

app.MapPost("/nonnullable", (Person person) =>
{
    return Results.Ok($"Received: {person.Name}, {person.Age}");
});

app.Run();

public class Person
{
    public string Name { get; set; } = default!;
    public int Age { get; set; }
}

In previous versions, two different schemas were emitted for the Person type, one annotated as nullable and one not.

While technically accurate, this presented challenges for code generators that assume a one to one mapping between a schema definition and a type declaration.

In .NET 10, the way nullability is represented in the schema changes to use the "type" keyword instead of the "nullable" keyword so we can use "allOf" to model this composition pattern.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-openapi

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions