Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .Net Core Web API with JsonPatchDocument

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

like image 562
R4nc1d Avatar asked Apr 21 '16 11:04

R4nc1d


People also ask

What is difference between web API and .NET Core?

In ASP.NET Core, there's no longer any distinction between MVC and Web APIs. There's only ASP.NET MVC, which includes support for view-based scenarios, API endpoints, and Razor Pages (and other variations like health checks and SignalR). In addition to being consistent and unified within ASP.NET Core, APIs built in .

What is API and why we are using API with .NET Core?

API stands for Application Programming Interface. It is an intermediate software agent that allows two or more applications to interact with each other.


1 Answers

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.

like image 117
Ralf Bönning Avatar answered Oct 12 '22 14:10

Ralf Bönning