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

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
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)