Mark strings as non-nullable in ASP.NET Core 3.0 Swagger

微笑、不失礼 提交于 2021-02-07 13:14:51

问题


I'm using ASP.NET Core 3 and Swashbuckle with mostly default configuration and I have a DTO parameter with a string on it that I want to be non-nullable. How can I achieve this? Note, Required and nullability are separate concerns in Swagger.

It's also using C#8 and the non-nullable stuff, so the compiler should be annotating the property as non-nullable already. It's understandable that Swashbuckle hasn't been updated to take that into account (and maybe can't) but I would like to be able to override the generated metadata somehow.

class MyDto {
    [Required]
    // I want this to show as non-nullable in the swagger documentation (and ideally also be non-nullable in the binding)
    public string TestProp { get; set; }
}

[HttpPost]
public void Post([FromBody] MyDto requestModel) {
}

I have tried making it Required. I also tried adding the Newtonsoft annotations, but none of these seemed to do it.

Relevant bit of Swagger doc that is generated:

    "MyDto": {
      "required": [
        "testProp"
      ],
      "type": "object",
      "properties": {
        "testProp": {
          "type": "string",
          "nullable": true
        }
      },
      "additionalProperties": false
     }

Note that having a string parameter directly as a parameter doesn't generate the nullable attribute. E.g.

[HttpPost("testPost")]
public void Post([FromBody] [Required] string testProp) {
}

will generate

"/api/test/testPost": {
  "post": {
    "tags": [
      "Test"
    ],
    "requestBody": {
      "content": {
        "application/json": {
          "schema": {
            "type": "string"
          }
        },
        "text/json": {
          "schema": {
            "type": "string"
          }
        },
        "application/*+json": {
          "schema": {
            "type": "string"
          }
        }
      },
      "required": true
    },
    "responses": {
      "200": {
        "description": "Success"
      }
    }
  }
},

回答1:


Until v4.01 nullable:true was emitted for optional strings. This broke in the first 5.0 RC versions and nullable:true wasn't emitted at all for optional strings. That, obviously, is wrong.

Starting with 5.0 RC3 optional strings are nullable once again.

To specify that an optional string is not nullable, you need to add [JsonProperty(Required = Required.DisallowNull)] to the property. Copying from one of Swashbuckle's unit tests, this :

    [JsonProperty(Required = Required.DisallowNull)]
    public string StringWithRequiredDisallowNull { get; set; }

Should set the property's Nullable flag :

Assert.False(schema.Properties["StringWithRequiredDisallowNull"].Nullable);

And emit nullable:true.



来源:https://stackoverflow.com/questions/58299772/mark-strings-as-non-nullable-in-asp-net-core-3-0-swagger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!