You can now use nullable reference types to mark strings as optional or required:
-
Enable nullable reference types for your project/solution
-
Mark strings in Dtos as nullable:
public class ExampleDto { [StringLength(64, MinimumLength = 4)] public string RequiredString { get; set; } [StringLength(200)] public string? OptionalString { get; set; } }
-
Enable Swagger support in your
Startup.cs
services.AddSwaggerGen(options => { options.SupportNonNullableReferenceTypes(); });
This leads to:
{
"Example": {
"type": "object",
"properties": {
"requiredString": {
"maxLength": 64,
"minLength": 4,
"type": "string"
},
"optionalString": {
"maxLength": 200,
"minLength": 0,
"type": "string",
"nullable": true
}
},
"additionalProperties": false
}
}