I'm creating a .NET Core Web API and want to call an endpoint submitting a customer order. The customer id comes as a route parameter. In the request body it's possible to send an array of objects. Each object contains the product id and its amount. But this field is optional, empty orders are possible too (products can be added later on).
So I started with this DTO
public class CreateCustomerOrderByIdDto
{
[FromRoute]
public uint Id { get; set; }
[FromBody]
public OrderPosition[] OrderPositions { get; set; }
}
public class OrderPosition
{
[Range(1, uint.MaxValue)]
public uint ProductId { get; set; }
[Range(1, uint.MaxValue)]
public uint Amount { get; set; }
}
This request DTO should make the OrderPositions field optional but when adding an item both properties are required for that item. I want to set a default value for OrderPositions if missing so I thought this data annotation would do it
[DefaultValue(new OrderPosition[0])]
Unfortunately I get this error message
An attribute argument must be a constant expression, 'typeof()' expression or array creation expression of an attribute parameter type
So how do you mark that field as optional and set a default value?
When passing no order positions the array will be transformed to an empty one so I can avoid null checks and work with loops that just never run