Reputation: 3772
I have a .NET Core Web API project and want to validate route parameters before running business logic. Given this sample endpoint
[HttpGet("{username:maxlength(30)}")]
public async Task<ActionResult<object>> GetUser([FromRoute] string username)
{
// ...
}
the username will never be greater than 30 characters. When calling the endpoint with a username longer than 30 characters the API will respond with a 404 response. I would expect a 400 with a message like
'username' must be greater than 0 and smaller than 31 characters
Am I wrong? Are there any reasons for this?
Upvotes: 1
Views: 1309
Reputation: 27793
Route constraints are used to disambiguate similar routes, if constraints are used for input validation, invalid input results in a 404 Not Found response.
For more information, please check: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.1#route-constraint-reference
To produce a 400 Bad Request for invalid input(s), as mentioned in comments, some built-in attribute, such as StringLength
etc can help achieve the requirement.
Upvotes: 2