PATCH request
- How-to
- Marco Meoni
- .NET DataStore
- Thursday, 3 March 2022 09:39 PM UTC
Hello,
Controller/Service scaffolding in SnapDevelop API generates HttpPost method that can also be used for HttpPut, i.e. for updating only one row of a given model (which is a must for non-PB REST client):
// Controller
[HttpPut]
public async Task<ActionResult<int>> UpdateAsync([FromBody]Employee employee)
//Service
public async Task<int> UpdateAsync(Employee employee,CancellationToken cancellationToken)
{
var dataStore = await this.RetrieveByKeyAsync(new object[] {employee.emp_id},cancellationToken);
dataStore.SetModel(0, employee);
return await dataStore.UpdateAsync(cancellationToken);
}
Now, cients can send JSON to http://localhost/api/employee/1 as PUT request and the DB update works fine, because .NET datastore SetModel() sets the data of Employee object to the first row of the DataStore:
{
emp_id: 1,
emp_lname: "Smith",
emp_fname: "John",
emp_deptid: 100,
[...]
}
Instead of PUT, (non-PB) clients better send a PATCH verb because it allows for partial updates:
{
emp_id: 1,
emp_deptid: 200
}
but with this body the Controller returns all the fields in the model object that are nulls except emp_deptid, which makes sense since it is saying I want a Models.Employee object.
Is there a way to detect which properties have actually been sent in the JSON request so I can update only those fields?
The "silly" solution is to test all properties in the JSON and keep old values in the TModel (e.g. Employee) if not sent by the client, but this requires per-model implementation.
Am I missing a .NET datastore method that does this trick?
Microsoft suggests to use JsonPatchDocument in the Patch action of a Controller, but this goes beyond the datastore API:
[FromBody]JsonPatchDocument<Employee> employee
Thanks,
.m
Find Questions by Tag
Helpful?
If a reply or comment is helpful for you, please don’t hesitate to click the Helpful button. This action is further confirmation of their invaluable contribution to the Appeon Community.