在将返回类型声明为 T
的 MVC/API 控制器操作中返回 ActionResult<TValue> 时,ObjectResult.StatusCode 始终设置为 200(当 T
为 ProblemDetails 时除外)。
此更改可能会导致在手动设置状态代码的某些情况下出现意外行为,因为以前 ObjectResult.StatusCode 是 null
。 此外,如果一个操作过滤器期望接收 null 值而不是 200,那么它可能会受到此更改的影响。
已引入的版本
ASP.NET Core 6.0
以前的行为
以前,控制器的操作返回T
并手动设置Response.StatusCode
以生成指定的响应状态代码。 例如,以下控制器的作将生成 202 Accepted
响应。
// Generates a 202 Accepted response
public ActionResult<Model> Get()
{
Response.StatusCode = StatusCodes.Status202Accepted;
return new Model();
}
新行为
现在,返回 T
并设置 Response.StatusCode
的同一控制器操作始终会生成 200 OK
响应。
// Generates a 200 OK response
public ActionResult<Model> Get()
{
Response.StatusCode = StatusCodes.Status202Accepted;
return new Model();
}
破坏性变更的类型
此更改可能会影响 源兼容性。
更改原因
返回 200 OK
状态代码的操作自 ASP.NET Core 3.1 以来已记录。 但是,它保持 StatusCode 原样 null
并最终生成 200 OK
响应,因为它是默认值。 由于默认内部行为可能会更改,因此我们决定避免依赖默认值并显式设置为 StatusCode 预期 200 OK
。
建议的措施
如果您的代码手动设置了状态码并因此更改而受到影响,则需要更改控制器动作。 例如,以下代码片段将状态代码设置为 202,并因该更改而中断。
public ActionResult<Model> Get()
{
Response.StatusCode = StatusCodes.Status202Accepted;
return new Model();
}
为了保留 202 状态代码的所需行为,以下代码片段显示了一些选项。
public ActionResult<Model> Get()
{
return Accepted(new Model());
}
// or
public ActionResult<Model> Get()
{
return StatusCode(StatusCodes.Status202Accepted, new Model());
}
// or
public Model Get()
{
Response.StatusCode = StatusCodes.Status202Accepted;
return new Model();
}
受影响的 API
- MVC/API 控制器操作