Question3r
Question3r

Reputation: 3772

Why does the API return a 404 instead of a 400 if a route parameter validation fails when using route constraints

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

Answers (1)

Fei Han
Fei Han

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

Related Questions