Partial Entity Updates in WebAPI PUT/POST

前端 未结 2 2025
梦如初夏
梦如初夏 2020-12-24 08:38

Say you have a repository method to update a Document:

public Document UpdateDocument(Document document)
  {
  Document serverDocument = _db.Documents.Find(         


        
2条回答
  •  半阙折子戏
    2020-12-24 09:17

    The best practice in API design is to use HTTP PATCH for partial updates. In fact, use cases like yours are the very reason why IETF introduced it in the first place.

    RFC 5789 defines it very precisely:

    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 has written a great article about the use of PATCH in API design - http://www.mnot.net/blog/2012/09/05/patch

    In your case, that would be:

      [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;
      }
    

提交回复
热议问题