5

I'm looking for a way to validate and check the values of the model that is sent to my PATCH method for updating. I haven't found my answer yet.

I've read the JsonPatch Documentation but I didn't find what I want.

Scenario: I have a RESTful Web API, and say I have a resource named "users". Say a client wants to partially update a "user" resource: (PATCH api/users/{id}), when the client sends a JsonPatch Document, for example, I have to check if the email is sent for updating and if yes, I have to check if the email wasn't duplicate. So, how could I do this in a method like below: (I use ASP.NET Web API)

[HttpPatch]
[Route("{userId}")]
public HttpResponseMessage UpdateUser(int userId, JsonPatch.JsonPatchDocument<User> patchDocument)
{
    // I could do this but before that I wanna validate the proeprties:
    patchDocument.ApplyUpdatesTo(dbContext.Users.Single(u => u.Id == userId));
}
Arad Alvand
  • 8,607
  • 10
  • 51
  • 71
  • 1
    You could consider applying the update to the object and then validating. if invalid then do not save changes to context. – Nkosi Oct 03 '18 at 20:51
  • @Nkosi Thanks but what if I want to do authorization before saving changes? Say only admins can change the "IsActive" property, and say I can check if the user is admin or not by using "CurrentUser.IsInRole("Admin")". Therefore, how can I check if the sent request has the request for changing "IsActive" property? – Arad Alvand Oct 04 '18 at 10:16
  • 2
    Then I think you would need to inspect the patch manually and apply your validation rules before applying updates – Nkosi Oct 04 '18 at 10:18

0 Answers0