1

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?

Question3r
  • 2,166
  • 19
  • 100
  • 200

1 Answers1

2

Could you not try the route constraint min?

[HttpPatch("{id:int:min(1)}/last-name")]

Also maybe the Id property can be a uint if you want to be strict elsewhere.

Sachin
  • 106
  • 1
  • 4
  • the constraint and hint for uint are perfect! – Question3r Jun 05 '20 at 08:11
  • do you know if there is a route constraint for such uints? I couldn't find one, so I started another thread... https://stackoverflow.com/questions/62211646/ready-to-use-uint-route-constraint – Question3r Jun 05 '20 at 09:53