Immutable Properties With JSON Patch in AspNet Core
There is now a NuGet package for this: Tingle.AspNetCore.JsonPatch.NewtonsoftJson
There are times you want ot make updates to a resource on the server without replacing the whole of it. JSON Patch works a great deal in this, lighter and very powerful. To learn more on JSON Patch check out these links below:
- Official site at http://jsonpatch.com
- Introductory Article by Kevin Sookocheff
- Explainer by Waqat Mansor
ASP.NET Core supports JSON Patch natively using the HttpPatchAttribute
usually decorate on a controller action with [HttpPatch]
, model binding support for JsonPatchDocument
and JsonPatchDocument<T>
, and model validation support when applying changes via extension method with the signature document.ApplyTo(document, ModelState)
. More on this can be found in the official documentation.
On this post I will not focus on how JSON Patch works, why it is better or how it is supported in ASP.NET Core (for that, see above links). Instead, I will focus on how you can ensure that certain properties are not edited in a patch operation or ensure that only certain properties can be edited.
TLDR; you can jump straight to the code.