introduction
In modern Web API development, we often need to partially update resources (Partial Update). TraditionalPUT
The request will require the entire object to be sent, andPATCH
Requests can only send fields that need to be updated. Core providesJsonPatchDocument<T>
To simplify this operation.
What is JsonPatch?
JsonPatch (based onRFC 6902) is a patch document in JSON format that allows the client to declaratively modify JSON resources. JsonPatch provides the following operations:
add
: Add a new value
remove
: Delete a field
replace
: Replace the value of a field
move
: Move a value
copy
: Copy a value
test
: Test whether a value meets expectations
Using JsonPatch in Core Web API
Installation dependence
JsonPatch
Built in, you need to make sure your project references the package:
().AddNewtonsoftJson();
Create API Controller
Suppose we have oneProduct
kind:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Then, createProductsController
deal withPATCH
ask:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List<Product> _products = new()
{
new Product { Id = 1, Name = "Laptop", Price = 1200 },
new Product { Id = 2, Name = "Mouse", Price = 25 }
};
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<Product> patchDoc)
{
var product = _products.FirstOrDefault(p => == id);
if (product == null)
{
return NotFound();
}
(product, ModelState);
if (!)
{
return BadRequest(ModelState);
}
return Ok(product);
}
}
Send a JsonPatch request
The client can send the followingPATCH
ask:
[
{ "op": "replace", "path": "/price", "value": 999.99 }
]
Example cURL request:
curl -X PATCH "http://localhost:5000/api/products/1" \
-H "Content-Type: application/json" \
-d '[{"op": "replace", "path": "/price", "value": 999.99}]'
Handle possible problems with JsonPatch
Make sure the JSON format is correct
JsonPatch syntax is prone to errors, such as incorrect or missing path formatop
. It is recommended to use Postman or cURL for debugging.
Handling ModelState errors
if(product, ModelState);
Returns an error, should returnBadRequest(ModelState)
and provide detailed error information.
in conclusion
JsonPatch
Provides an elegant way to partial updates avoidingPUT
Redundancy of the entire object is required. Reasonable useJsonPatch
, can improve the flexibility and efficiency of the API.