0
votes

I am implementing HTTP Patch using JsonPatch library from .NET Core.(Microsoft.AspNetCore.Mvc.NewtonsoftJson). MS Doc: https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-5.0

Am able to do partial updates using JsonPatch with the below code.

DTO:

public class Customer{
   public int Id;
   public string Name;
   public string ZipCode;
}

Controller:

[HttpPatch]
public IActionResult JsonPatchWithModelState([FromBody] JsonPatchDocument<Customer> patchDoc)
{
   var customer = GetExistingCustomerFromDatabase();
   patchDoc.ApplyTo(customer, ModelState);

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

    return new ObjectResult(customer);
}

Sample Postman: (Valid data scenario) [Name property updated as expected]

Request:
{
  "op":"replace",
  "path": "/name",
  "value": "updated-name-XYZ"
}

Response: 200(OK)

When the value of "Name" property is an invalid data type; below response is returned.

Sample Postman: (Invalid data Scenario) [For example: Trying to pass a dictionary object]

Request:
{
  "op":"replace",
  "path": "/name",
  "value": {"key123": "value123"}
}

Response: 400(Bad Request)
Response Body:
{
    "Customer": [
        "The value '{\r\n  \"key123\": \"value123\"\r\n}' is invalid for target location."
    ]
}

When the above request is sent to the HTTP action method, the breakpoint hits. At that instant ModelState.IsValid = true, after patch is applied:

 patchDoc.ApplyTo(customer, ModelState);

ModelState.IsValid becomes false. And BadRequest(400) is returned.

Is there a way to catch this invalid data type even before patch is applied to get a detailed error message. Or does JsonPatch support throwing specific error message at property level(here: "Name"), instead of entity level(here: "Customer")?

Required response body:

Response: 400(Bad Request)
Response Body:
{
    "Name": [
        "The input was not valid."
    ]
}

This is the error message for POST or PUT during invalid data scenario.

And Breakpoint will not be hit at action method, due to the serializable error:

"Executing ObjectResult, writing value of type '\"Microsoft.AspNetCore.Mvc.SerializableError\"'.", "Type":"Microsoft.AspNetCore.Mvc.SerializableError"

Can similar behavior be achieved with JsonPatch also? Is there way to catch serializable errors with DTO classes while using JsonPatchDocument?

Or any custom validator approaches will be helpful.

1

1 Answers

0
votes
{
  "id" : 1,
  "name":{
           "key123": "value123"
         }
}

Try to replace the value at key not name with a new value.

{
  "op":"replace",
  "path": "/name/key123",
  "value": "value1234"
}