So this is an example endpoint to fetch one user by its username
[HttpGet("{username}")]
public async Task<ActionResult<object>> GetUser([FromRoute] string username)
{
// ...
}
Regardless of the value of username
the database will either find and return a user or null. But you know that a username has validation constraints like
- max length of x
- no special characters
- ...
So you could also add a validation route constraint e.g.
[HttpGet("{username:maxlength(20)}")]
or make use of data annotations like
[FromRoute][MaxLength(20)] string username
but then you have to do it for every endpoint. The advantage is that bad parameter values will never touch the database so you might increase the performance because the request gets denied. The bad thing is that you will have to maintain all these endpoints with extra validations instead of saying "I don't care for the value, the database will find it or not.".
Are there any best practises which approach should be considered?