当客户端尝试更新资源时,如果 URI 的 id 与正文的 id 不同,应该如何响应? 例如:
URI:
PUT /members/123
body
{
id : 456,
name : "john"
}
最佳答案
https://www.rfc-editor.org/rfc/rfc7231#section-4.3.4
An origin server SHOULD verify that the PUT representation is consistent with any constraints the server has for the target resource that cannot or will not be changed by the PUT. This is particularly important when the origin server uses internal configuration information related to the URI in order to set the values for representation metadata on GET responses. When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable. The 409 (Conflict) or 415 (Unsupported Media Type) status codes are suggested, with the latter being specific to constraints on Content-Type values.
正文中的 id 应与资源标识符匹配的要求(或等效地,资源标识符不可变的要求)将算作对资源的约束。因此,如果是这种情况,您应该保留整个 资源不变,并返回 409 和一条错误消息。
也就是说,没有特别的理由表明标识符和表示需要有任何共同的数据。想想 HashMap /字典/键值存储。将状态 id:456
存储在键 /members/123
下没有任何问题。如果这在您的资源模型中是合适的,则将新表示放入存储中并返回 200。
关于rest - PUT URI 的 id 不同于 body 的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38769013/