0

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?

1
  • You'll need to change your int ProductId to a nullable int like int? ProductId as explained here Commented Jun 5, 2020 at 7:02

1 Answer 1

1

You need to use Range on the ProductId as well. If your ProductId starts from 1 then it would look like below:

[Required]
[Range(1, int.MaxValue)]
public int ProductId { get; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your reply. So the correct fix for this is public class OrderPosition { [Required] [Range(1, int.MaxValue)] public int ProductId { get; set; } [Required] [Range(1, int.MaxValue)] public int Amount { get; set; } } ? because with a range starting at 0 it just takes the default value for integers?
[Required] seems to be redundant, because the Range attribute seems to handle it. But what if you would want to validate an optional field only if set? Currently the Range attribute would mark that field as required
Right you can remove Required, And you can keep the Amount's range from 0 unless 1 is the minimum Amount you expect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.