8

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://learn.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);
    }
}
Shane
  • 83
  • 1
  • 4
  • You seem to be mixing ASP .NET Core code and older ASP.NET MVC code as ModelStateDictionary should be in the Microsoft.AspNetCore.Mvc namespace and not System.Web.Http. If you want to use ASP .NET Core remove all references to System.Web.*.dlls. If you are using ASP .NET MVC you would need to write a wrapper to convert between ASP .NET Core and ASP .NET MVC ModelStateDictionaries. In ASP .NET Core ControllerBase or Controller base classes are in the Microsoft.AspNetCore.Mvc namespace, whereas in ASP.NET MVC they are in System.Web.Mvc namespace. Both are incompatible with each other. – ckuri Sep 14 '19 at 07:00
  • 1
    @Steve writes in an [answer here](https://stackoverflow.com/a/60289407/3744182): *this is the issue reference from documentation https://github.com/aspnet/AspNetCore.Docs/issues/16286*. (Just in case the answer is removed as a link-only answer). – dbc Feb 18 '20 at 21:10

4 Answers4

10

You have to add Newtonsoft package for .Net Core

Microsoft.AspNetCore.Mvc.NewtonsoftJson

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Hassan Rahman
  • 4,953
  • 1
  • 34
  • 32
2

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();
Francis
  • 21
  • 3
1

I solved this by adding the following NuGet Package to my project:

Microsoft.AspNetCore.Mvc.NewtonsoftJson

keikai
  • 14,085
  • 9
  • 49
  • 68
dlasalde
  • 21
  • 1
0

if you have asp.net V6 or V7 for fix this problem need install packed the packed name is : Microsoft.AspNetCore.Mvc.NewtonsoftJson

after install packed ypu need add service is program.cs

builder.Services.AddControllers() .AddNewtonsoftJson();