简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM