0

I am currently trying to figure out how I could prevent the user of my API to change/update a specific property. From what I was able to gather from the web was that it is simply not supported, at least by the Microsoft implementation Microsoft.AspNetCore.JsonPatch. Other than that I was able to find the IObjectAdapter interface which would allow me to add some custom logic in the ApplyTo method. However that seems like a pretty ugly approach.

Obviously I could also use GraphQL, however that would be somewhat overkill for those few times I really need it. Would there be any alternative?

Twenty
  • 4,232
  • 3
  • 24
  • 56
  • So your purpose is to update only some fields when updating model in the api? If so, you can limit the `IsModified` attribute to some special fields when updating, please refer to: https://stackoverflow.com/a/17570001/12884742 – LouraQ Aug 11 '20 at 02:57
  • @YongqingYu That would work, however I am not using EF Core. Therefor that really won't help me. – Twenty Aug 11 '20 at 07:42

2 Answers2

0

After some digging around on GitHub I was able to found a gem called JsonPath.Patchable by Labradoratory which exactly fixes the issue I am having. Although it does break the DDD pattern which doesn't really makes me to happy, but is pretty much the best we can get to.

Update

I just created a nuget package, which solves this problem, by providing extension methods which allow you to pass in specific properties which are allowed to be changed. Example:

public class DummyModel
{
    public int Id { get; set; }
    public string Value { get; set; }
}

var patchDocument = new JsonPatchDocument();
patchDocument.Replace("/Value", "newValue");

patchDocument.ApplyToWithRestrictions(dummy, "Value"); // Allows the Patch to only modify the Value property. This argument takes an array.

The source code to this package is available here.

Twenty
  • 4,232
  • 3
  • 24
  • 56
0

Have you try restriction by specifying the class serialization, for example

public class UpdatableDummyModel
{
    public string Value { get; set; }
}

and your input is

JsonPatchDocument<UpdatableDummyModel>
Joe
  • 2,121
  • 1
  • 16
  • 16
  • That would require me to parse it to a "updateable model" first and then convert it back to the real type. That's also a bit of an ugly work around IMHO. – Twenty Mar 25 '22 at 19:01