- RFC 7396
- Backed by Newtonsoft.Json or System.Text.Json - your choice
- Supports conversion to JSON Patch, which can perform partial resource updates
- Supports Swagger
- .Net 5
Some inspiring projects:
C# Object | JSON | Resulting C# Object |
var person = new Person()
{
FirstName = "John",
LastName = "Doe"
}; |
{
"LastName": "Smith"
} |
{
FirstName = "John",
LastName = "Smith"
} |
// Apply all the changes in the patch to your existing DTO
[HttpPatch]
[Consumes(MergePatchDocument.ContentType)]
public IActionResult Patch([FromBody] IJsonMergePatch<Person> mergePatch)
{
...
mergePatch.ToJsonPatch().ApplyTo(existingDTO);
...
}
//Acting on the presence/absence of a property in the patch
[HttpPatch]
[Consumes(MergePatchDocument.ContentType)]
public IActionResult Patch([FromBody] IJsonMergePatch<Person> mergePatch)
{
if(mergePatch.TryGetValue(x => x.LastName, out var ln)
{
//act accordingly
}
}
// If you need to create a patch document to call a different service
public void CreatePatch()
{
//simple sets, one property at a time
var mergePatch = JsonMergePatch.New();
mergePatch.Set(x => x.LastName, "Smith");
//or, use a builder, which can conditionally set values from other merge patchess
var pb = JsonMergePatch.CreateBuilder<Person>();
pb.Set(x => x.LastName).ToValue("Smith");
var mergePatch = pb.Build();
}