Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Validation With Web API and JSON Patch Document

I'm using JsonPatchDocument with ASP.NET 4.5 and Web Api. My controller looks like this:

[HttpPatch]
[Route("MyRoute/{PersonItem1}/{PersonItem2}/")]
public IHttpActionResult ChangePerson([FromHeader]Headers, [FromBody]JsonPatchDocument<PersonDto> person)
{
    // Do some stuff with "person"
}

And PersonDto:

public class PersonDto
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Now, I may send a PATCH request that is something like:

{
    "op": "op": "replace", "path": "/email", "value": "[email protected]"
}

Now let's say I add some data annotations:

public class PersonDto
{
    public string Name { get; set; }

    [MaxLength(30)]
    public string Email { get; set; }
}

What is the best way to ensure this validation is honored without writing additional validation. Is it even possible?

like image 890
Jamie Counsell Avatar asked May 13 '16 18:05

Jamie Counsell


People also ask

What is a JSON Patch document?

JSON Patch is a format for specifying updates to be applied to a resource. A JSON Patch document has an array of operations. Each operation identifies a particular type of change. Examples of such changes include adding an array element or replacing a property value.

What is application JSON Patch JSON?

JSON Patch is a web standard format for describing changes in a JSON document. It is meant to be used together with HTTP Patch which allows for the modification of existing HTTP resources. The JSON Patch media type is application/json-patch+json . JSON Patch. Filename extension.

Which of the following is used to check the validity of the model in Web API?

You can use the Validate() method of the ApiController class to manually validate the model and set the ModelState.


1 Answers

There is the simple method:

  1. Get your object from your repository.
  2. Deep copy the object so you have object A and B.
  3. Apply the change with person.ApplyUpdatesTo(objB).
  4. Create an extension method to validate the difference between object A and B.
  5. If the validation is good proceede, if not throw an error.

This would catch if the client was attempting to modify immutable fields or if the new information in object B violates your constraints.

Note that this is not a great solution in that you would have to change your code in two places if you happen to change your constraints.

like image 62
Betsalel Williamson Avatar answered Oct 23 '22 16:10

Betsalel Williamson