ASP.NET Web API: How to handle partial update requests?

Chris B 1 Reputation point
2022-12-05T13:59:14.083+00:00

Hi,

I'm wondering how to handle update requests in my API, where the request does not necessarily include all the properties that the API is able to update.
The API might be able to receive a DTO with 10 properties, but if your JSON only contains 5 of those, the remaining ones will be considered null.
This might lead to null being written into the database, even though the property wasn't actually present in the request and not supposed to be changed at all.
Generally though, actually passing a property with null as its value is absolutely fine and should be updated accordingly.

So the main question is, how to differentiate between null values and not present values?

Regards,
Chris

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,735 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 69,276 Reputation points
    2022-12-05T16:56:15.893+00:00

    c# is not the easiest language for this. you will want to preserve the json structure:

    using StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8);
    var jsonString = reader.ReadToEndAsync();

    then parse to JObject or JsonElement depending on your json library of choice. your code can then walk json tree and build insert/update statements based on the request.

    if the updates are not random collection of values, then you can use custom request / response classes and build a transaction oriented api.

    note: you should never use DTO classes as action parameters.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.