public Document UpdateDocument(Document document) { Document serverDocument = _db.Documents.Find(document.Id); serverDocument.Title = document.Title; serverDocument.Content = document.Content; _db.SaveChanges(); return serverDocument; }
在这种情况下,实体有两个属性.更新文档时,JSON请求中都需要这两个属性,因此请求PUT / api /文件夹与一个
{ "documentId" = "1","title" = "Updated Title" }
将返回错误,因为没有提供“内容”.我这样做的原因是因为即使用户不能更新的可空属性和属性,强制客户端在请求中指定这些字段似乎更安全,以避免用空服务器覆盖未指定的字段.
这导致我在PUT和POST请求中始终要求每个可更新属性的做法,即使这意味着为这些属性指定null.
这是很酷,还是有一个我还没有学到的模式/实践,这可能通过发送只需要通过电线来促进部分更新?
解决方法
事实上,像你这样的用例是IETF首先介绍它的原因.
RFC 5789定义非常精确:
PATCH is used to apply partial modifications to a resource.
A new method is necessary to improve interoperability and prevent
errors. The PUT method is already defined to overwrite a resource
with a complete new body,and cannot be reused to do partial changes.
Otherwise,proxies and caches,and even clients and servers,may get
confused as to the result of the operation. POST is already used but
without broad interoperability (for one,there is no standard way to
discover patch format support).
Mark Nottingham在API设计 – http://www.mnot.net/blog/2012/09/05/patch中写了一篇关于使用PATCH的伟大文章
在你的情况下,那将是:
[AcceptVerbs("PATCH")] public Document PatchDocument(Document document) { Document serverDocument = _db.Documents.Find(document.Id); serverDocument.Title = document.Title; serverDocument.Content = document.Content; _db.SaveChanges(); return serverDocument; }