11

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I am looking for something like a filter that would not require me to write such code in each controller, but this is a good start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.