I started with an API endpoint to create a new order for one customer by its customer id
[HttpPost("{id:int}/orders")]
public async Task<ActionResult<object>> CreateCustomerOrderByIdAsync(CreateCustomerOrderByIdDto createCustomerOrderByIdDto)
{
// ...
}
So the DTO itself should validate the whole request. The customer id is a required field, the order positions are optional, the order itself can be empty.
public class CreateCustomerOrderByIdDto
{
[FromRoute]
[Required]
public int Id { get; set; }
[FromBody]
public OrderPosition[] OrderPositions { get; set; }
}
Each OrderPositions knows about the ProductId and the Amount. Both fields are required for this instance in the array.
public class OrderPosition
{
[Required]
public int ProductId { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int Amount { get; set; }
}
When I call the endpoint https://localhost:5001/customers/1/orders with the following json body
{
"orderPositions": [{}]
}
I would expect a 400 because the array holds an object with no ProductId or Amount field. But instead of the error it takes the default value for integers which is 0. How can I validate each OrderPosition inside the OrderPositions array too?
int ProductIdto a nullable int likeint? ProductIdas explained here