Using .Net Core Web API with JsonPatchDocument

R4nc1d picture R4nc1d · Apr 21, 2016 · Viewed 17k times · Source

I am using JsonPatchDocument to update my entities, this works well if the JSON looks like the following

[
  { "op": "replace", "path": "/leadStatus", "value": "2" },
]

When i create the object it converts it with the Operations node

var patchDoc = new JsonPatchDocument<LeadTransDetail>();
patchDoc.Replace("leadStatus", statusId); 

{
  "Operations": [
    {
      "value": 2,
      "path": "/leadStatus",
      "op": "replace",
      "from": "string"
    }
  ]
}

if the JSON object looks like that the Patch does not work. I believe that i need to convert it using

public static void ConfigureApis(HttpConfiguration config)
{
    config.Formatters.Add(new JsonPatchFormatter());
}

And that should sort it out, the problem is i am using .net core so not 100% sure where to add the JsonPatchFormatter

Answer

Ralf B&#246;nning picture Ralf Bönning · Jul 18, 2016

I created the following sample controller using the version 1.0 of ASP.NET Core. If I send your JSON-Patch-Request

[
  { "op": "replace", "path": "/leadStatus", "value": "2" },
]

then after calling ApplyTo the property leadStatus will be changed. No need to configure JsonPatchFormatter. A good blog post by Ben Foster helped me a lot in gaining a more solid understanding - http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates

public class PatchController : Controller
{
    [HttpPatch]
    public IActionResult Patch([FromBody] JsonPatchDocument<LeadTransDetail> patchDocument)
    {
        if (!ModelState.IsValid)
        {
            return new BadRequestObjectResult(ModelState);
        }


        var leadTransDetail = new LeadTransDetail
        {
            LeadStatus = 5
        };

        patchDocument.ApplyTo(leadTransDetail, ModelState);

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

        return Ok(leadTransDetail);
    }
}

public class LeadTransDetail
{
    public int LeadStatus { get; set; }
}

Hope this helps.