How to return a BadRequest when the return type is not an ActionResult?

Viewed 1861

It seems that the HttpGet method's return type need not be an ActionResult. For example, the following method works:

[HttpGet]
[Route("list")]
public async Task<IEnumerable<MyItem>> List()

But then, how can I return a BadRequest (BadRequest("...")) in this case?

1 Answers

If you really have to respond with BadRequest from within the controller method, you can use the following approach as recommended by Microsoft here

[HttpGet("list")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<MyItem>))]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async IActionResult List()
{
  // Code to validate request
  if(requestIsValid)
  {
    // Code to get IEnumerable of MyItems
    return Ok(myItems);
  }
  else
  {
    return BadRequest()
  } 
}
Related