http - 由于乐观锁定失败,使用哪个 HTTP 状态代码来拒绝 PUT

标签 http rest web optimistic-locking

假设我想实现某种乐观锁定并使用 ETag 来指示最新的资源状态。这意味着,当 PUT 更新时,客户端将使用 If-Match header 。

根据HTTP spec ,如果为 If-Match header 提供的 ETag 与资源的当前状态不匹配,服务器必须返回 412 Precondition failed

然而,409 Conflict似乎更接近我想要表达的语义,特别是因为它给出了响应中包含的内容的指南。

在无法匹配 If-Match header 中提供的 ETag 的情况下返回 409 是不是非常错误?

最佳答案

从您的规范链接:

If none of the entity tags match, or if "*" is given and no current entity exists, the server MUST NOT perform the requested method, and MUST return a 412 (Precondition Failed) response. This behavior is most useful when the client wants to prevent an updating method, such as PUT, from modifying a resource that has changed since the client last retrieved it.

因为规范要求 HTTP 412(实际上它使用“MUST”),并且很明显它们准确地说明了正在讨论的用例,所以 HTTP 412 似乎是正确的响应代码。

412 还是很合理的。该请求说要有条件地进行更新。 412 表示条件失败,因此服务不会这样做。特别是因为 412 非常适合条件请求的概念; 409 似乎与特定类型的拒绝有关,这种拒绝本质上可能是有条件的,也可能不是。例如,我可以看到服务返回 409 以响应无条件请求以发布具有内部冲突的内容。

但请参阅规范中的以下内容:

10.4.10 409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

无论如何,规范似乎在条件请求上下文中需要 412,同时表明版本冲突是 409 的关键驱动因素。作为无条件请求的一部分,可能会在发生版本冲突的地方使用 409。

关于http - 由于乐观锁定失败,使用哪个 HTTP 状态代码来拒绝 PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122088/

相关文章:

json - POST 到 foursquare API 的示例?

java - 如何使用 REST API 创建 JIRA 问题,并将受让人设置为未分配

wordpress - 如何获取 woocommerce 的所有产品?

javascript - 如何聚焦 HTML 表格中的行?

javascript - 在 Angular2 中实现基于角色的访问

security - 在对 < 和 > 进行编码时,html 标记之间是否可能发生 xss 攻击

java - 在 Android 中从服务器获取和发送数据的最佳方法

java - Android中如何使用HttpURLConnection来发布数据?

c# - 不调用 Response.Flush 仍然发送连接 : Close in the Response

java - 如何在 Java 中从 Stripe 接收 Webhook