22

I am using ASP.NET and Swagger that exposes a complex type that accepts a POST. It has a number of string fields that have different restricted lengths. How can I reflect that in the Swagger UI?

illug
  • 793
  • 1
  • 9
  • 23

1 Answers1

30

You can annotate the properties with the StringLengthAttribute from System.ComponentModel.DataAnnotations.

For instance:

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

will become:

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

And this:

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

becomes:

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

Besides StringLength Swashbuckle also supports the Range and RegularExpression attributes.

Update

MaxLength does not work. StringLength does. However, discovering this information in Swagger UI is a bit clumsy. You have to navigate to the Model of your object and then hover over the property:

How to discover max length info

venerik
  • 5,766
  • 2
  • 33
  • 43
  • Thanks. I was using the MaxLength attribute. But neither display the "maxLength": 10 part in the Swagger UI. – illug Mar 17 '16 at 13:54
  • I agree it is a bit clumsy. The hover bit doesn't even really work when you have more then one of these annotations. They will stack on top of each other and you don't know to which field they are referring. Thank for a great answer though. – illug Mar 21 '16 at 16:31
  • The latest version stable version of `Swashbuckle` incorporates a new version of `Swagger UI` that fixes the stacked boxes. – venerik Nov 08 '16 at 17:37
  • 1
    Check out ReDoc, it a lot nicer than Swagger UI, only thing still missing for me is interactive api console. – David De Sloovere Dec 15 '16 at 14:42
  • 2
    MaxLength works for ASP.NET core and Swashbuckle at least now. Still have to hover to see max length unfortunately. – Richard Collette Feb 21 '18 at 23:45
  • I can confirm that MaxLength and MinLength work in current Core 2.2. – Jpsy Dec 19 '18 at 10:16
  • Thanks. This works well and shows maxlength when you hover over it but when I type string in input control it allows me to type characters more than the maximum length. I am using Swashbuckle 5.6.0 for ASP .Net application. – Manmath Feb 22 '19 at 09:22
  • What this becomes? [Description("26\"")] TwentySix = 1 – A Coder Jun 03 '19 at 10:35