1

I have a web API with the following model:

public class ParseLicenseRequest
{
    public const string emptyStringDefault = "";

    [Required(AllowEmptyStrings = false)]
    public string LicenseKey { get; set; }

    [DefaultValue(emptyStringDefault)]
    public string Sid { get; set; } = emptyStringDefault;

    public bool ShortFormat { get; set; }
}

When compiling the code, it looks like this in swagger:

enter image description here

I am trying to set the default value of sid to be empty:

"sid" : ""

However, it doesn't set the default value to empty.

Dana Griff
  • 155
  • 1
  • 7

1 Answers1

1

I think you could add custom ISchemaFilter to modify your Example value:

Note: Not sure what is your version of the Swagger,different swagger will make the parameter in Apply() different.

public class CustomSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(ParseLicenseRequest))
        {
            schema.Example = new OpenApiObject
            {
                ["Sid"] = new OpenApiString("")
            };
        }

    }
}

Register the filter in Startup.cs:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebapiProject5", Version = "v1" });
    c.SchemaFilter<CustomSchemaFilter>();

});

Reference:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#apply-schema-filters-to-specific-types

Rena
  • 30,832
  • 6
  • 37
  • 72