加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – WebAPI PUT / POST中的部分实体更新

发布时间:2020-12-15 23:17:30 所属栏目:asp.Net 来源:网络整理
导读:假设您有一个存储库方法来更新文档: public Document UpdateDocument(Document document) { Document serverDocument = _db.Documents.Find(document.Id); serverDocument.Title = document.Title; serverDocument.Content = document.Content; _db.SaveCha
假设您有一个存储库方法来更新文档:
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.

这是很酷,还是有一个我还没有学到的模式/实践,这可能通过发送只需要通过电线来促进部分更新?

解决方法

API设计中的最佳做法是使用HTTP PATCH进行部分更新.
事实上,像你这样的用例是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;
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读