Using .Net Core Web API with JsonPatchDocument

18,793

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.

Share:
18,793

Related videos on Youtube

R4nc1d
Author by

R4nc1d

Updated on June 19, 2022

Comments

  • R4nc1d
    R4nc1d almost 2 years

    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