【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属性 - 隐式强制转换运算符支持将
T和ActionResult均转换为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()
}

浙公网安备 33010602011771号