Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ModelState with JsonPatchDocument.Applyto

Tags:

c#

json-patch

I see in the Microsoft docs and many examples where they call JsonPatchDocument.ApplyTo(patchObject, ModelState), but I can't seem to get it to build that way. I get a build error saying "Error CS1503 Argument 2: cannot convert from 'System.Web.Http.ModelBinding.ModelStateDictionary' to 'System.Action'"

I'm referencing Microsoft.AspNetCore.JsonPatch v2.2.0 and the sample code is from here:

https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-2.2

[HttpPatch]
public IActionResult JsonPatchWithModelState(
    [FromBody] JsonPatchDocument<Customer> patchDoc)
{
    if (patchDoc != null)
    {
        var customer = CreateCustomer();

        patchDoc.ApplyTo(customer, ModelState);

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        return new ObjectResult(customer);
    }
    else
    {
        return BadRequest(ModelState);
    }
}
like image 662
Shane Avatar asked Sep 13 '19 20:09

Shane


2 Answers

You have to add Newtonsoft package for .Net Core

Microsoft.AspNetCore.Mvc.NewtonsoftJson

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
like image 200
Hassan Rahman Avatar answered Oct 12 '22 15:10

Hassan Rahman


You have to install this NuGet package:

Microsoft.AspNetCore.Mvc.NewtonsoftJson

You also have to add these method calls to the ConfigureServices method in the Startup class:

services
    .AddControllersWithViews()
    .AddNewtonsoftJson();
like image 20
Francis Avatar answered Oct 12 '22 13:10

Francis