2

I am creating an HTTP Partial method in my ASP.NET Web API controller and I read this document http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates on how to achieve HTTP Partial methods in a controller. I get an exception when I hit the HTTP Partial endpoint that says enter image description here

Here is my code for the Patch method in the controller:

[HttpPatch("{userId}")]
public IActionResult Patch([FromRoute(Name = "userId")]Guid userId, [FromBody] JsonPatchDocument<User> userProperties)
{
    var indexOfUserToPartiallyUpdate = UsersInMemory.List.FindIndex(user => user.Id == userId);

    if (indexOfUserToPartiallyUpdate == -1)
    {
        return BadRequest($"user with {userId} not found.");
    }

    var originalUser = UsersInMemory.List[indexOfUserToPartiallyUpdate];

    userProperties.ApplyTo(UsersInMemory.List[indexOfUserToPartiallyUpdate], ModelState);

    if (!ModelState.IsValid)
    {  
        return new BadRequestObjectResult(ModelState);
    }

    var model = new
    {
        beforePatch = originalUser,
        afterPatch = UsersInMemory.List[indexOfUserToPartiallyUpdate]
    };

    return Ok(model);
}

And here is the JSON body I'm sending through postman in the HTTP PATCH request:

enter image description here

I feel like I need to do something in the Startup.cs file such as configuring the JsonPatchDocument but I don't know how. Any help is much appreciated.

1 Answer 1

5

I think i found your issue: "Note that we always send an array of operations even if you're only sending a single operation."

Try to change your request in:

[
  {
    "op": "replace",
    "path": "/email",
    "value": "[email protected]"
  }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Okay Thank you Vadim. I will try it out later after work and let you know if that is a solution.
That worked Vadim. Thank you very much for your response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.