Search code examples
c#asp.net-coreroutesasp.net-core-webapiasp.net-core-2.2

Api call constraint reference for multiple params not honored


Only the first constraint reference, {userid:guid:required} is validated when calling the API.

The second parameter, {key:maxlength(5):required} is not validated. What is wrong here, is this a framework bug?

[HttpDelete("{userid:guid:required}/{key:maxlength(5):required}")]
[Route("deletefavorite")]
public ActionResult<Favorites> DeleteFavorites([FromQuery]Guid userId, [FromQuery]string key)
{
    if (!ModelState.IsValid) return BadRequest(ModelState);

    return NotFound($"Error 404: Could not delete {key}");
}

I'm building a .Net Core 2.2 API for an Single Page Application(SPA)


Solution

  •     using System.ComponentModel.DataAnnotations;
    
        [Route("deletefavorite")]
        public ActionResult<Favorites> DeleteFavorites([FromQuery][Required]Guid userId, [FromQuery][Required][MaxLength(5)]string key)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);
    
            return NotFound($"Error 404: Could not delete {key}");
        }
    

    Output

    {
        "key": ["The field key must be a string or array type with a maximum length of '5'."]
    }