【ASP.NET Core】Action返回结果(IActionResult、ActionResult<T>)

Action返回类型

特定类型

返回类型是特定类型,状态码是200,如果想返回其他的HTTP状态码类型,只能设置ResponseStatusCode,不优雅

public Person Person1([FromQuery] int id = 1)
{
    if (id != 1)
    {
        Response.StatusCode = 404;
    }
    return new Person { ID = id };
}

IActionResult

public IActionResult Person2([FromQuery] int id = 1)
{
    if (id!=1)
    {
        return NotFound();
    }
    return Ok(new Person { ID = 1 });
}

ActionResult

它支持返回从 ActionResult 派生的类型或返回特定类型。 ActionResult<T> 通过 IActionResult 类型可提供以下优势:

  • 可排除 [ProducesResponseType] 特性的 Type 属性
  • 隐式强制转换运算符支持将 TActionResult 均转换为 ActionResult<T>。 将 T 转换为 ObjectResult,也就是将 return new ObjectResult(T); 简化为 return T
public ActionResult<Person> Person3([FromQuery] int id = 1)
{
    if (id != 1)
    {
        return NotFound();
    }
    return new Person { ID = 1 };//可以省略OK()
}
posted @ 2019-12-15 23:17  .Neterr  阅读(538)  评论(0编辑  收藏  举报