问题描述
更准确地说:
根据rest风格,一般假设CREATE、READ、UPDATE和DELETE(CRUD)操作应该使用POST、GET、PUT和DELETE http方法.
According to rest style, it's generally assummed that POST, GET, PUT, and DELETE http methods should be used for CREATE, READ, UPDATE and DELETE (CRUD) operations.
事实上,如果我们坚持http方法的定义,事情可能不会那么清楚
In fact, if we stick to the http methods definition the thing might not be so clear
在这篇文章中的解释是:
简而言之:当且仅当您知道资源所在的 URL 以及资源的全部内容时才使用 PUT.否则,使用 POST.
主要是因为
PUT 是一个限制性更强的动词.它需要一个完整的资源并将其存储在给定的 URL 中.如果之前有资源,则替换它;如果没有,则创建一个新的.这些属性支持幂等性,而简单的创建或更新操作可能不支持幂等性.我怀疑这可能就是为什么 PUT 被定义为这样的原因;这是一种幂等操作,允许客户端向服务器发送信息.
在我的情况下,我通常发布传递所有资源数据的更新,因此我可以使用 PUT 进行更新,但是每次我发布更新时,我都会保存一个 LastUser 和 LastUpdate 列,其中包含进行修改的用户 ID 和时间 od操作.
In my case I usually issue updates passing all the resource data, so I could use PUT for updates, but everytime I issue an update I save a LastUser and LastUpdate column, with the user id that made the modification and the time od the operation.
所以我想知道你的意见,因为严格来说这两列不是资源的一部分,但它们确实阻止了操作的幂等性.
So i'd like to know your opinion, because strictly speaking those two columns are not part of the resource, but they do prevent the operation from being idempotent.
问候
sas
推荐答案
忽略关于 REST 风格将 CRUD 映射到 HTTP 方法的评论,这是一个很好的问题.
Ignoring the comment about the REST style mapping CRUD to the HTTP methods, this is an excellent question.
您的问题的答案是,是的,您可以在这种情况下自由使用 PUT,即使服务器以非幂等方式更新了某些资源元素.不幸的是,答案背后的推理相当模糊.重要的是要了解客户端请求的意图.客户端打算用传递的值完全替换资源的内容.客户端不负责服务器执行其他操作,因此不违反 HTTP 方法的语义.
The answer to your question is, yes you are free to use PUT in this scenario even though there are some elements of the resource that are updated by the server in a non-idempotent manner. Unfortunately, the reasoning behind the answer is quite vague. The important thing, is to understand what was the intent of the client request. The client intended to completely replace the contents of resource with the values passed. The client is not responsible for the server doing other operations and therefore the semantics of the HTTP method are not violated.
这是用于在您执行 GET 操作时允许服务器更新页面计数器的推理.客户端没有要求更新,因此即使服务器选择进行更新,GET 也是安全的.
This is the reasoning that is used to allow a server to update a page counter when you do a GET operation. The client didn't ask for an update therefore the GET is safe even though the server chose to make an update.
完整的资源与部分资源的争论终于在 HTTP 规范
The whole, complete resource versus partial resource debate has finally been spelled out in an update to the HTTP spec
源服务器应该拒绝任何 PUT请求包含一个Content-Range 头字段,因为它可能会被误解为部分内容(或可能是部分内容被错误地 PUT 作为充分代表).部分内容更新是可能的单独标识的资源重叠部分的状态更大的资源,或通过使用不同的方法已经专门为部分定义更新(例如,PATCH[RFC5789]中定义的方法).
所以,我们现在应该做的事情已经很清楚了.不太清楚的是为什么存在只允许发送完整响应的限制.这个问题已经被问到,恕我直言,在这个关于休息讨论的线程中仍然没有答案.
So, what we are supposed to do is now clear. What is not so clear is why there exists this constraint on only being allowed to send full responses. That question has been asked and IMHO remains unanswered in this thread on rest-discuss.
这篇关于如果我还更新时间戳属性,我应该使用 PUT 方法进行更新吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!