'How to set default values for a query param with array type in .Net.Core with Swashbuckle by code

I am currently working with .NET Core 3.1 and Swashbuckle library. I have made several endpoints with requests decorated with attributes and proper swagger descriptions (I want to continue doing it this way).

Now I have a problem with the query parameter whose type is Array. It is no problem to show this property with items to add. enter image description here I wish to fulfill them with default 12 values. It could be 12 x 0. Something like:

[DefaultValue(new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })]

Also, I set [MaxLength(12)], but it also does not work.

I see for now even validation for numbers does not work.

For now, it looks like this:

    /// <summary>
    /// MyArray with 12x0 values.
    /// </summary>
    [DefaultValue(new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })]
    [MaxLength(12)]
    [Range(0, 1)]
    public int[] MyArray { get; set; }

What do I want to achieve?

  • default values for 12 items with 0.
  • no less and no more than 12 items.
  • validation is in range 0,1

Thank you in advance!

Edit: I have also tried custom AttributeFilter, but it changes nothing on swagger UI...

 public class QueryArrayParameterFilter : IParameterFilter
{
    public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
    {
        if (!parameter.In.HasValue || parameter.In.Value != ParameterLocation.Query)
            return;

        if (parameter.Schema?.Type == "array" && parameter.Name.Equals("MyArray"))
        {
            var value = null as IOpenApiExtension;
            parameter.Extensions.TryGetValue("explode", out value);

            if (value == null)
            {
                parameter.Extensions.Add("explode", new OpenApiBoolean(false));
            }

            parameter.Schema = new OpenApiSchema
            {
                Type = "array",
                Items = new OpenApiSchema()
                {
                    MaxItems = 2,
                    Type = "integer",
                    Format = "int64",
                    Example = new OpenApiArray() 
                    {
                    new OpenApiInteger(0),
                    new OpenApiInteger(0)
                    },
                    Default = new OpenApiArray()
                    {
                    new OpenApiInteger(0),
                    new OpenApiInteger(0)
                    }
                },
                MaxItems = 3
            };
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source