因有效业务原因而失败的有效请求的 "correct" HTTP 状态代码是什么?

What's the "correct" HTTP status code for valid request that fail for a valid business reason?

想听听您的意见,可能没有绝对正确的答案,但我想看看您认为哪种方法更正确。

如果请求在结构上没有任何错误(格式正确)并且所有字段都有效(字段值不太长,必填字段有值等...)但由于业务原因,例如 "you cannot change a status of task that isn't assigned to you",在这种情况下应该如何响应:

  1. 200 和 JSON 解释错误:
{
  error: {
    code :120,
    message: "you cannot change a status of a task that isn't assigned to you"
  }
}
  1. 或者可能是具有类似正文的 4xx 响应:
{
  error: {
    code :120,
    message: "you cannot change a status of a task that isn't assigned to you"
  }
}

403 Forbidden 看起来很合适

来自 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4.

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

因此,您提出的选项 2 似乎不错,因为它还描述了失败的原因。

虽然我想同意@EJK,但他链接的规范已经过时了。

最新的是 RFC7231:https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1 它改变了 old 403 FORBIDDEN 响应状态的含义。

答案:

因此,为了这个问题,应该使用 400 BadRequest,因为使用您的服务的任何人,如果是客户,都是错误的,并且可以解决他的请求

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

您自己的用例示例:

客户现在知道错误"you cannot change a status of a task that isn't assigned to you"是他自己的错。他甚至可能会尝试发出不同的新(有效)请求。