Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable property is not presented in the Swashbuckle.AspNetCore openapi schema properly

Using Swashbuckle.AspNetCore v6.0.7 in an asp.net core project net5.0.

Let say I have models like these:

public enum MyEnum
{
  A, B
}

and

public class MyModel 
{
   public MyEnum MyEnum { get; set; }
   public MyEnum? MyEnum2 { get; set; }
}

and the swagger schema is generated like this:

"MyEnum": {
        "enum": [
          "A",
          "B"
        ],
        "type": "string"
      },
      "MyModel": {
        "type": "object",
        "properties": {
          "myEnum": {
            "$ref": "#/components/schemas/MyEnum"
          },
          "myEnum2": {
            "$ref": "#/components/schemas/MyEnum"
          }
        },
        "additionalProperties": false
      }

As you can see, there is no difference between MyEnum and MyEnum? in the open-API JSON schema!

And seems nullable enum is not presented in the schema properly.

Does anyone have any idea how can I fix this?

Best

like image 334
Majid Parvin Avatar asked Feb 03 '26 05:02

Majid Parvin


2 Answers

As Yiyi You suggested, I called UseAllOfToExtendReferenceSchemas in SwaggerGenOptions like this:

services.AddSwaggerGen(c =>
{
       c.UseAllOfToExtendReferenceSchemas();
});

and now the schema is generated like:

"MyEnum": {
        "enum": [
          "A",
          "B"
        ],
        "type": "string"
      },
      "MyModel": {
        "type": "object",
        "properties": {
          "myEnum": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MyEnum"
              }
            ]
          },
          "myEnum2": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MyEnum"
              }
            ],
            "nullable": true
          }
        },
        "additionalProperties": false
      },

and there is "nullable": true for the type MyEnum?.

You can find more information here.

like image 171
Majid Parvin Avatar answered Feb 05 '26 00:02

Majid Parvin


The following worked well for me:

_ = services.AddSwaggerGen(c =>
{
    // Enables support for nullable object properties
    c.UseAllOfToExtendReferenceSchemas();
    // Enable detection of non nullable reference types to set Nullable flag accordingly on schema properties
    c.SupportNonNullableReferenceTypes();
})
like image 30
aleksander_si Avatar answered Feb 04 '26 23:02

aleksander_si



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!