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

Viewed 2857

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

1 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.

Thanks to Yiyi You.

Related