简体   繁体   English

是否应该始终在HTTP PUT请求中的url和body中验证资源ID?

[英]Should we always validate resource id in url and body in HTTP PUT request?

Suppose I am updating a employee record 假设我正在更新员工记录

url - /api/employees/10 网址- /api/employees/10

body - 身体 -

{ 
  id : 10,
  name : xyz
}

Should I validate for the employee id in url is same as in response? 我应该验证url中的雇员ID是否与响应中的相同? Because one employee can hit the url himself but update the data of another employee by sending another value in the PUT body. 因为一个员工可以自己打URL,但可以通过在PUT正文中发送另一个值来更新另一位员工的数据。

If you have to validate, it's likely that you want to use POST. 如果必须验证,则可能要使用POST。 A POST is not idempotent and you are supposed to manage the change. POST不是幂等的,应该由您来管理更改。

PUT is idempotent, and it just creates a resource. PUT是幂等的,它只是创建资源。 It implies that you don't actually care what id 10 is and whether it is a new id or an existing id. 这意味着您实际上并不在乎ID 10是什么,无论它是新ID还是现有ID。 You just replace id 10 with the resource you supply. 您只需将ID 10替换为您提供的资源即可。 You only use PUT when you know what the uri should be. 仅当您知道uri应该是什么时,才使用PUT。

Yes, if the representation of the object in the body contains its own key, you should validate that it matches the key from the URL. 是的,如果对象在主体中的表示形式包含其自己的密钥,则应验证其是否与URL中的密钥匹配。 It's an error for the client to try to PUT an object at /api/employees/10 that isn't a valid value for employee #10's record, so you should check for that and report it as an error just as you would check that the object has correct syntax. 客户端尝试在/api/employees/10处放置一个对象而不是10号员工记录的有效值是错误的,因此您应该检查该对象并将其报告为错误,就像检查该对象一样。该对象具有正确的语法。

I believe that the best error code to return in this case is 422 Unprocessable Entity , but I might be wrong about that. 我相信在这种情况下返回的最佳错误代码是422 Unprocessable Entity ,但是我对此可能是错误的。

Another thing you can do instead is don't include the key at all in the body. 相反,您可以做的另一件事是根本不包含密钥。 However I find that keeping the key in makes sense for consistency with the way the same type of object is represented in other parts of the API (possibly embedded inside other objects). 但是,我发现保持键的合理性与API其他部分(可能嵌入其他对象中)表示同一类型对象的方式保持一致。 This is especially true when using XML (although it looks like you are using JSON here). 使用XML时尤其如此(尽管看起来您在这里使用JSON)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM