c# - 当返回类型不是 ActionResult 时如何返回 BadRequest?

标签 c# asp.net-core asp.net-web-api

看来HttpGet方法的返回类型不必是 ActionResult .例如,以下方法有效:

[HttpGet]
[Route("list")]
public async Task<IEnumerable<MyItem>> List()
但是,在这种情况下,我如何返回 BadRequest ( BadRequest("...") )?

最佳答案

如果你真的需要回复 BadRequest在 Controller 方法中,您可以使用 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()
  } 
}

关于c# - 当返回类型不是 ActionResult 时如何返回 BadRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67955500/

相关文章:

c# - 在代码中创建测试数据

c# - 在项目之间共享 DLL

asp.net-core - 如何在 ABP Core Zero 中使用多个数据库?

c# - 自托管webapi时如何设置http请求队列长度?

c# - 在 Controller 外部将HttpResponseMessage转换为HttpActionResult的最简单方法

c# - 如何从mysql读取一行?

c# - Windows.Forms Application.Run() 中无法追踪的异常

c# - Web API 通用操作

c# - HTTPClient 缓冲区超过 2G;无法向缓冲区写入更多字节

asp.net-core - 包 Microsoft.AspNetCore.Authentication.JwtBearer 5.0.0 与 netcoreapp3.1 不兼容,但它的目标是 net 5.0