I have an enum:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CommentStatus
{
New = 1,
Accepted = 2,
Rejected = 3
}
And a controller action:
[HttpPut("/comments/{commentId}/status")]
public async Task<IActionResult> ChangeCommentStatus(Guid commentId, [FromBody] CommentStatus commentStatus)
{
return NoContent();
}
The controller action should accept in a "commentStatus" parameter only values: New, Accepted, Rejected, 1, 2, 3
But now it accepts also values out of range, for example: 999 Why?
A view from Postman:
A view from Visual Studio:
CodePudding user response:
A switch on the enum should do the trick:
switch (commentStatus)
{
case CommentStatus.New:
case CommentStatus.Accepted:
case CommentStatus.Rejected:
return NoContent();
default:
return BadRequest();
}
Not ideal but at least you get control on what the response should be.
CodePudding user response:
You could just use switch statement to validate the commentStatus e.g
[HttpPut("/comments/{commentId}/status")]
public async Task<IActionResult> ChangeCommentStatus(Guid commentId, [FromBody] CommentStatus commentStatus)
{
switch(commentStatus)
{
case CommentStatus.New:
//do new stuff
break;
case CommentStatus.Accepted:
//do accepted stuff
break;
case CommentStatus.Rejected:
//do rejected stuff
break;
default:
//invalid type of comment status
break;
}
return NoContent();
}
CodePudding user response:
Depend on the framework you are using to have a different approach but basically, you can add some filter to validate the model before executing the actions.
For aspcore
For asp.net