'Ignore JsonPatch specific property

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?



Solution 1:[1]

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.

Solution 2:[2]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Joe