【问题标题】:Nullable property is not presented in the Swashbuckle.AspNetCore openapi schema properlySwashbuckle.AspNetCore openapi 架构中未正确显示可空属性
【发布时间】:2021-03-02 15:16:54
【问题描述】:

asp.net core 项目net5.0 中使用Swashbuckle.AspNetCore v6.0.7

假设我有这样的模型:

public enum MyEnum
{
  A, B
}

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

并且swagger架构是这样生成的:

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

如您所见,MyEnumMyEnum? 在 open-API JSON 架构中没有区别!

而且似乎可以为空的枚举未正确显示在架构中。

有人知道我该如何解决这个问题吗?

最好的

【问题讨论】:

  • 您可以参考link,并尝试使用UseAllOfToExtendReferenceSchemas(),正如domaindrivendev所说。

标签: c# asp.net-core swagger swashbuckle.aspnetcore


【解决方案1】:

正如Yiyi You建议的那样,我在SwaggerGenOptions 中调用了UseAllOfToExtendReferenceSchemas,如下所示:

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

现在生成的模式如下:

"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
      },

"nullable": true 对应于类型 MyEnum?

您可以找到更多信息here

感谢Yiyi You

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多