Home > Blockchain >  What's wrong with my PATCH request body in Swagger?
What's wrong with my PATCH request body in Swagger?

Time:10-05

I'm trying to implement PATCH operation for my WebAPI. I'm trying to update using PATCH.

My controller looks like this:

[HttpPatch("update/{id}")]
public async Task<ActionResult> UpdateSite(int id, [FromBody]JsonPatchDocument<Site> sitePatch)

This is my Site class:

public class Site
{
    public int id { get; set; }
    public string site_name { get; set; }
}

This is what I'm putting in my request body in Swagger:

{
  "op": "replace",
  "path": "site_name",
  "value": "FOOO"
}
// I have also tried with: "path": "/site_name"

When the code hits the controller, I see the sitePatch variable is always empty, it has 0 Operations. What did I do wrong?

CodePudding user response:

A JSON Patch document (JsonPatchDocument<T>) has an array of operation object(s).

You do have a valid operation object but it is not in an array, so it is not being deserialised correctly.

The below JSON should populate sitePatch as expected:

[
    {
      "op": "replace",
      "path": "site_name",
      "value": "FOOO"
    }
]

CodePudding user response:

I've totally missed this:

services
.AddControllersWithViews()
.AddNewtonsoftJson();

Then it works.

  • Related