So given this sample endpoint to update the last name of a customer
[HttpPatch("{id:int}/last-name")]
public async Task<ActionResult<object>> UpdateCustomerLastNameByIdAsync(UpdateCustomerLastNameByIdDto updateCustomerLastNameByIdDto)
{
// ...
}
I created this DTO to validate the id and the last name.
public class UpdateCustomerLastNameByIdDto
{
[FromRoute]
public int Id { get; set; }
[FromBody]
[StringLength(50, MinimumLength = 1)]
[Required]
public string LastName { get; set; }
}
So the validation for LastName
works fine as expected. But when calling the endpoint with this url https://localhost:5001/customers/-5/last-name I would expect the ID to be -5.
Tow problems come up:
- When debugging the Id field it's not -5, it's 0. Maybe the url parameter conversion casts it to 0 when below?
- My Ids start at 1 so 1 should be the minimum
I added the attribute [Range(1, int.MaxValue)]
to the Id field in the DTO. When calling the url again it works fine. When calling the url https://localhost:5001/customers/123/last-name I get a 400 with the following output
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3d8afda-4ef45dce3935e1e0.",
"errors": {
"Id": [
"The field Id must be between 1 and 2147483647."
]
}
}
123 should be a valid id. So how do I validate the id param to be a required positive integer starting at 1?