How to use ModelState with JsonPatchDocument.Applyto
Asked Answered
E

4

9

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);
    }
}
Extremist answered 13/9, 2019 at 20:19 Comment(2)
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.Fanning
@Steve writes in an answer here: this is the issue reference from documentation github.com/aspnet/AspNetCore.Docs/issues/16286. (Just in case the answer is removed as a link-only answer).Jemappes
D
11

You have to add Newtonsoft package for .Net Core

Microsoft.AspNetCore.Mvc.NewtonsoftJson

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Doe answered 25/2, 2020 at 13:1 Comment(0)
F
3

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();
Fink answered 10/5, 2020 at 20:9 Comment(0)
B
2

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

Microsoft.AspNetCore.Mvc.NewtonsoftJson

Bombast answered 12/2, 2020 at 23:58 Comment(0)
L
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();

Longboat answered 30/11, 2022 at 17:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.