Wednesday 18 September 2019

JsonPatchDocument in ASP.NET Core web API to use PATCH verb

Recently got chance to work with PATCH verb in DotNetCore, which allow us to update model partially. Nice reference could be found on Official Microsoft and Dotnetcoretutorials.

In short, we just need to understand PATCH Operations, make valid JSON patch request and correct implementation of JsonPatchDocument in dotnetcore action.

Operation details could be found here ,


And make call to endpoint with valid request, like in below request I just want to update the userName as Raj.

JSON Request:
[
  {
    "op": "replace",
    "path": "/userName",
    "value": "Raj"
  }
]


JsonPatchDocument Implementation in dotnet core API

/// <summary>
         /// Jsons the state of the patch with model.
         /// </summary>
         /// <param name="userId">The user identifier.</param>
         /// <param name="userPatch">The user patch.</param>
         /// <returns>Updated user</returns>
         [HttpPatch]
         public async Task<IActionResultPatchUserAsync(int userId, [FromBodyJsonPatchDocument<UserDtouserPatch)
         {
             if (userPatch != null)
             {
                 //Get existing user from DB through service or repository.
                 var user = await _userService.GetUserAsync(userId); 
                 //Apply patch to existing user.
                 userPatch.ApplyTo(user);
  
                 //Again validate model
                 if (!ModelState.IsValid)
                 {
                     return BadRequest(ModelState);
                 }
  
                 //Update user through service or repository.
                 await _userService.UpdateUserAsync(UserId, user);
  
                 //Return updated user.
                 return new ObjectResult(user);
             }
             else
             {
                 return BadRequest(ModelState);
             }
         }