-1

I'm getting a 400 Bad Request when trying to calling a PATCH endpoint on my Web API (.Net Core 3.1) and I cannot figure out why. My action method looks like this:

using Microsoft.AspNetCore.JsonPatch;

namespace PropWorx.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]    
    public class OwnersController : ControllerBase

        [HttpPatch("{id:int}")]
        public async Task<ActionResult<Owner>> PatchOwner([FromRoute] int id, [FromBody] JsonPatchDocument<Owner> patchDoc)
        {
            if (patchDoc == null)
                return BadRequest(ModelState);

            var owner = await _context.Owners.FindAsync(id);

            if (owner == null)
            {
                return NotFound();
            }

            patchDoc.ApplyTo(owner, ModelState);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            await _context.SaveChangesAsync();

            return new ObjectResult(owner);
        }
    }
}

And I am sending this to it in Postman:

{
  "Op": "replace",
  "Path": "/PropertyInspectId",
  "Value": 10764
}

(I've also tried a string "10764" instead of an integer)

(Please see image below)

PropertyInspectId is a nullable integer and is definitely in the model and correctly spelt. I get the 400 error response immediately - before my API's action method even executes the first line of code.

enter image description here

Any ideas?

Fabricio Rodriguez
  • 3,769
  • 11
  • 48
  • 101
  • 2
    Did you read the error? A JSON patch is an array. – CodeCaster Aug 13 '20 at 13:00
  • Thanks CodeCaster. That was indeed the issue. To answer your question, I did read the error, but the error just said "One or more validation errors occurred.". I didn't see any mention of the problem being that it was not an array. – Fabricio Rodriguez Aug 13 '20 at 13:02
  • Thanks again CodeCaster, yes that indeed helped me out. I honestly did Google this problem but I regrettably didn't come across the page you sent me. I don't know how i could've missed that page... But anyway, thank you. It's working now – Fabricio Rodriguez Aug 13 '20 at 13:05

1 Answers1

0

As per the comment by @CodeCaster the problem was that an JSON PATCH is an array. I was sending through a single entity in Postman. A user on this link CodeCaster provided me had the same issue: An error when sending PATCH with Postman to Asp.net Core webapi

Fabricio Rodriguez
  • 3,769
  • 11
  • 48
  • 101