Swagger 中的数据注释

Data annotations in Swagger

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

您可以使用 System.ComponentModel.DataAnnotations 中的 StringLengthAttribute 注释属性。

例如:

[StringLength(10)]
public String Name {get;set;}

将变为:

"name": {
    "minLength": 0,
    "maxLength": 10,
    "type": "string"
}

还有这个:

[StringLength(10, MinimumLength = 5)]
public String Name {get;set;}

变为:

"name": {
    "minLength": 5,
    "maxLength": 10,
    "type": "string"
}

除了 StringLength Swashbuckle 还支持 RangeRegularExpression 属性。

更新

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