Using .Net Core Web API with JsonPatchDocument

I use JsonPatchDocument to update my objects, this works well if JSON looks like this

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

When I create an object, it transforms it using 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 the fix is โ€‹โ€‹not working. I believe that I need to convert it using

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

And that should figure it out, the problem is that I'm using the .net kernel, so I'm not 100% sure where to add JsonPatchFormatter

+5
source share
1 answer

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

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

then after calling ApplyTo, the leadStatus property will be changed. No need to configure JsonPatchFormatter. A good blog post from Ben Foster helped me gain a deeper 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.

0
source

Source: https://habr.com/ru/post/1247607/


All Articles