Swagger中的数据注释

ill*_*lug 18 asp.net-web-api2 swagger-2.0 swashbuckle

我使用ASP.NET和Swagger公开了一个接受POST的复杂类型.它有许多具有不同限制长度的字符串字段.我怎样才能在Swagger UI中反映出来?

ven*_*rik 25

您可以使用StringLengthAttributefrom 注释属性System.ComponentModel.DataAnnotations.

例如:

[StringLength(10)]
public String Name {get;set;}
Run Code Online (Sandbox Code Playgroud)

会变成:

"name": {
    "minLength": 0,
    "maxLength": 10,
    "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

还有这个:

[StringLength(10, MinimumLength = 5)]
public String Name {get;set;}
Run Code Online (Sandbox Code Playgroud)

变为:

"name": {
    "minLength": 5,
    "maxLength": 10,
    "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

除了StringLengthSwashbuckle还支持RangeRegularExpression属性.

更新

MaxLength不起作用.StringLength确实.但是,在Swagger UI中发现这些信息有点笨拙.您必须导航到Model对象的对象,然后将鼠标悬停在属性上:

如何发现最大长度信息

  • MaxLength至少现在可以用于ASP.NET core和Swashbuckle。仍然必须悬停才能看到最大长度。 (2认同)