Home > Blockchain >  How can I don't allow my api to not accept values out of range for a parameter type of enum?
How can I don't allow my api to not accept values out of range for a parameter type of enum?

Time:02-21

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:

enter image description here

A view from Visual Studio:

enter image description here

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

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0#:~:text=The OnActionExecuting action filter can be used to:

For asp.net

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

  • Related