PUT as full replacement vs PATCH as partial update, JSON Patch vs JSON Merge Patch, the missing-vs-null problem, and implementing PATCH in ASP.NET Core 10 with System.Text.Json, validation and concurrency.
PUT replaces the whole resource with the representation sent, so anything omitted is reset; it is idempotent. PATCH sends only the changes.
Two standard PATCH formats exist:
null means remove. Simple, but can't express array edits or set a value to null.replace, add, remove, test). Precise, but verbose.The hard part is missing vs null: a normal C# DTO can't tell them apart, so you read JsonElement/JsonNode or use JsonPatchDocument<T> (System.Text.Json-based since .NET 10). The trade-off: merge patch is friendlier for clients; JSON Patch is safer for arrays and conditional (test) updates.
"PUT means 'here is the full new representation, store it at this URI'. If the client leaves out
notes, the server should clearnotes. That makes PUT idempotent and simple to reason about, but clients must first GET the whole resource and send it all back, and older clients that don't know about a new field will wipe it. PATCH means 'apply these changes'. RFC 5789 doesn't define the format, so you pick a media type. JSON Merge Patch,application/merge-patch+json, is a partial document: fields present are set,nullremoves. JSON Patch,application/json-patch+json, is an array of operations likereplace /statusortest /version, applied in order and atomically.The implementation trap is missing versus null. If I bind merge patch into a C# record,
{\"notes\": null}and{}both giveNotes == null, so I can't tell 'clear it' from 'leave it'. I either read the body asJsonElementand checkTryGetProperty, or use JSON Patch. On .NET 10 there'sMicrosoft.AspNetCore.JsonPatch.SystemTextJson, soJsonPatchDocument<T>no longer needs Newtonsoft. Either way I patch a DTO, not the EF entity, validate the result, then map it, and I requireIf-Matchwith the ETag from arowversionso two editors don't silently overwrite each other.For example, at [company] our [customer profile] endpoint used PUT, and an older mobile app version that didn't know about the new
marketingConsentfield reset it to false on every save, about [3,000] profiles a week. We moved to merge patch for profile edits, addedIf-Match, and the overwrites stopped. The mistake I see is using PUT for partial updates, or patching entities directly, which is an over-posting hole."
| PUT | PATCH | |
|---|---|---|
| Semantics | Replace whole representation | Apply a set of changes |
| Idempotent | Yes | Not guaranteed |
| Payload | Full resource | Changes only |
| Unknown/new fields | Old clients wipe them | Untouched |
| Create if missing | Allowed (client-chosen id) | Possible but unusual |
| JSON Merge Patch (RFC 7396) | JSON Patch (RFC 6902) | |
|---|---|---|
| Media type | application/merge-patch+json |
application/json-patch+json |
| Shape | Partial document | Array of operations |
| Remove a field | "field": null |
{"op":"remove","path":"/field"} |
| Set a value to null | Impossible | replace with null |
| Array edits | Replace whole array | Add/remove by index, - for append |
| Conditional | No | test operation |
| Client friendliness | High | Lower |
Moving [profile edits] from PUT to merge patch with If-Match cut the average request size from [4 KB to 300 bytes] and eliminated the [~3,000 weekly] accidental resets caused by older app versions; 412 responses (about [0.2%] of edits) showed where real concurrent edits happened and the app now reloads and asks the user.
Checks whether the candidate understands PUT vs PATCH semantics, the two PATCH formats, and the practical implementation issues (missing vs null, over-posting, concurrency).
Green flags
Red flags
v1 client knows: { name, email }
v2 server has: { name, email, marketingConsent }
v1 client: GET -> { name, email, marketingConsent: true } (ignores unknown field)
PUT { name, email } (field dropped)
server: marketingConsent reset to default (false)
This is why many public APIs (e.g. Microsoft Graph) use PATCH for updates and reserve PUT for idempotent create-or-replace with client-chosen ids.
target: {"name":"Ana","phone":"0400 000 000","address":{"city":"Perth","postcode":"6000"}}
patch: {"phone":null,"address":{"city":"Fremantle"}}
result: {"name":"Ana","address":{"city":"Fremantle","postcode":"6000"}}
Objects merge recursively; any non-object value (including arrays) replaces; null deletes. Applying the same merge patch twice gives the same result, so merge patch is idempotent in practice, though the method isn't guaranteed to be.
[
{ "op": "test", "path": "/status", "value": "Draft" },
{ "op": "replace", "path": "/status", "value": "Submitted" },
{ "op": "add", "path": "/tags/-", "value": "urgent" }
]
Paths are JSON Pointers (RFC 6901). Operations apply in order and the whole patch must fail if any operation fails. test gives a lightweight precondition. add to /tags/- appends, so repeating it appends twice: not idempotent.
Until .NET 9, JsonPatchDocument<T> lived in Microsoft.AspNetCore.JsonPatch, required Newtonsoft.Json and AddNewtonsoftJson(). .NET 10 adds Microsoft.AspNetCore.JsonPatch.SystemTextJson, a System.Text.Json-based implementation (namespace Microsoft.AspNetCore.JsonPatch.SystemTextJson) with ApplyTo(target, onError). As of late 2026 it does not support dynamic/ExpandoObject targets, and you should still apply it to a DTO, not an entity. Because the patch can touch any path, restrict which paths are allowed or apply to a DTO that only contains editable fields.
{} -> Notes: null (meant: leave as is)
{"notes": null} -> Notes: null (meant: clear it)
Options:
| Technique | How | Trade-off |
|---|---|---|
JsonElement / JsonNode body |
TryGetProperty("notes", out var v) |
Manual mapping, no compile-time safety |
Optional<T> wrapper + custom converter |
Optional<string?> Notes with HasValue |
Extra type, converter to maintain |
| JSON Patch | Explicit operations | Verbose for clients |
PATCH is read-modify-write on the server. Without a precondition, two edits interleave and one is lost. Expose the SQL Server rowversion as an ETag, require If-Match, set it as the EF Core original value (entry.Property(e => e.RowVersion).OriginalValue = ...), and map DbUpdateConcurrencyException to 412. Return 428 Precondition Required if If-Match is missing on a resource that needs it.
Apply the patch to a DTO, then validate the DTO (DataAnnotations, FluentValidation or .NET 10 Minimal API validation), then map to the entity inside the transaction. Return 400/422 with ValidationProblemDetails if the patched result is invalid, and 400 if the patch document itself is malformed.
JsonElement and write tests for {}, {"notes":null} and {"notes":"x"}.Microsoft.AspNetCore.JsonPatch.SystemTextJson and apply a patch with a failing test operation; check nothing changes.If-Match value in an integration test and assert one gets 412.Merge patch with explicit missing-vs-null handling, ETag concurrency and validation of the patched DTO.
// Program.cs (.NET 10)
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<ProfileStore>();
var app = builder.Build();
app.MapMethods("/profiles/{id:int}", ["PATCH"], async (
int id, HttpRequest request, ProfileStore store, CancellationToken ct) =>
{
if (request.ContentType?.StartsWith("application/merge-patch+json") != true)
return Results.StatusCode(StatusCodes.Status415UnsupportedMediaType);
var current = store.Get(id);
if (current is null) return Results.NotFound();
// Optimistic concurrency: the client must send the ETag it last saw.
var ifMatch = request.Headers.IfMatch.ToString();
if (string.IsNullOrEmpty(ifMatch)) return Results.StatusCode(StatusCodes.Status428PreconditionRequired);
if (ifMatch != current.ETag) return Results.StatusCode(StatusCodes.Status412PreconditionFailed);
using var doc = await JsonDocument.ParseAsync(request.Body, cancellationToken: ct);
var patch = doc.RootElement;
// Missing property = leave alone; explicit null = clear (where allowed).
var updated = current.Data with
{
DisplayName = patch.TryGetProperty("displayName", out var dn) ? dn.GetString() ?? current.Data.DisplayName : current.Data.DisplayName,
Phone = patch.TryGetProperty("phone", out var ph) ? (ph.ValueKind == JsonValueKind.Null ? null : ph.GetString()) : current.Data.Phone,
MarketingConsent = patch.TryGetProperty("marketingConsent", out var mc) ? mc.GetBoolean() : current.Data.MarketingConsent
};
if (string.IsNullOrWhiteSpace(updated.DisplayName) || updated.DisplayName.Length > 100)
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["displayName"] = ["Display name is required and must be 100 characters or fewer."]
});
var saved = store.Save(id, updated);
request.HttpContext.Response.Headers.ETag = saved.ETag;
return Results.Ok(saved.Data);
});
app.Run();
public sealed record ProfileDto(string DisplayName, string? Phone, bool MarketingConsent);
public sealed record Versioned(ProfileDto Data, string ETag);
public sealed class ProfileStore
{
private readonly Dictionary<int, Versioned> _items = new()
{
[1] = new(new ProfileDto("Ana", "0400 000 000", true), "\"1\"")
};
private int _version = 1;
public Versioned? Get(int id) => _items.GetValueOrDefault(id);
public Versioned Save(int id, ProfileDto dto) => _items[id] = new(dto, $"\"{++_version}\"");
}
JSON Patch with the System.Text.Json implementation added in .NET 10 (package Microsoft.AspNetCore.JsonPatch.SystemTextJson), in an MVC controller:
using Microsoft.AspNetCore.JsonPatch.SystemTextJson;
using Microsoft.AspNetCore.Mvc;
[ApiController, Route("orders")]
public sealed class OrdersController(IOrderService orders) : ControllerBase
{
[HttpPatch("{id:int}")]
[Consumes("application/json-patch+json")]
public async Task<IActionResult> Patch(int id, [FromBody] JsonPatchDocument<EditOrderDto> patch, CancellationToken ct)
{
var dto = await orders.GetEditableAsync(id, ct); // a DTO with only editable fields
if (dto is null) return NotFound();
patch.ApplyTo(dto, error => ModelState.AddModelError(error.AffectedObject?.ToString() ?? "patch", error.ErrorMessage));
if (!ModelState.IsValid || !TryValidateModel(dto)) return ValidationProblem(ModelState);
await orders.UpdateAsync(id, dto, ct); // maps DTO -> entity, saves with rowversion check
return NoContent();
}
}
public sealed class EditOrderDto { public string Status { get; set; } = ""; public List<string> Tags { get; set; } = []; }
public interface IOrderService
{
Task<EditOrderDto?> GetEditableAsync(int id, CancellationToken ct);
Task UpdateAsync(int id, EditOrderDto dto, CancellationToken ct);
}
null, so you either clear fields by accident or can never clear them. Instead: JsonElement/JsonNode, an Optional<T> wrapper, or JSON Patch.JsonPatchDocument<T> to an EF Core entity. Why it is wrong: Clients can patch any path, including IsAdmin, TenantId or navigation properties (over-posting). Instead: Patch an edit DTO, validate it, then map.rowversion and If-Match; 412 on mismatch, 428 when missing.Microsoft.AspNetCore.JsonPatch.SystemTextJson.application/json for PATCH without saying which format. Why it is wrong: Clients guess the semantics. Instead: Require and document application/merge-patch+json or application/json-patch+json.remove /lines/2 removes whatever is at index 2 now, which may differ if another client changed the array. Instead: Combine with test or If-Match, or address array items by id through sub-resources.Most teams should default to JSON Merge Patch for simple field edits because clients find it natural, and reach for JSON Patch only when they need array edits, explicit nulls or test preconditions. Whatever format you choose, the safety comes from the same three things: patch a DTO not an entity, validate the result, and require If-Match.
The other senior consideration is evolution. PUT couples clients to the full shape of the resource, so adding a field becomes a breaking change for old clients that round-trip the representation. PATCH lets the resource grow without breaking anyone.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| PUT | Small, stable resources; client-chosen ids; idempotent upserts | Full payloads, old clients wipe new fields | Resources that evolve often |
| Merge Patch | Form-style edits of scalar fields | Can't set null, arrays replaced wholesale | Array manipulation |
| JSON Patch | Array edits, explicit nulls, conditional ops | Verbose, path-level authorisation needed | Simple mobile/web forms |
Task endpoints (POST /orders/42/submit) |
State transitions with business rules | More endpoints | Plain data edits |
GET reads, POST creates or runs a command, PUT replaces a resource at a known URI, PATCH partially updates it, DELETE removes it, HEAD is GET without the body, and OPTIONS asks what is allowed (used by CORS preflight).
These properties are a contract that caches, proxies, browsers and retry policies rely on: a gateway may retry a timed-out PUT but must not blindly retry a POST. Breaking the contract, such as changing state on GET, causes duplicate side effects and crawler disasters.
Optimistic concurrency assumes conflicts are rare: read the row with its rowversion, and when saving run UPDATE ... WHERE Id = @id AND RowVersion = @original. If 0 rows are affected, someone else changed it: return 409/412 and let the user reload or merge. No locks are held between read and write, so it suits web forms with user think time.
Pessimistic concurrency locks first: inside a short transaction, SELECT ... WITH (UPDLOCK, HOLDLOCK) so no one else can take the row until you commit; for job queues, UPDLOCK, READPAST lets workers skip claimed rows. sp_getapplock locks a logical name (e.g. 'invoice-run-2026-11') when there's no single row to lock.
The trade-off: optimistic costs retries under contention; pessimistic costs blocking and deadlock risk.
Ranked by severity: (1) over-posting: binding the EF entity lets a client set fields they shouldn't (IsApproved, Role, Price, Id, navigation properties), a security hole. (2) information disclosure: returning ex.Message can leak SQL, server names or personal data. (3) broken HTTP semantics: 200 with success: false makes failures look like successes to monitoring, retries, caches and clients. (4) swallowed exceptions: the catch-all hides bugs and usually doesn't log. (5) hand-rolled validation: inconsistent and duplicated. The rewrite: a request DTO with only the allowed fields, DataAnnotations with [ApiController] (or FluentValidation), explicit mapping to the entity, proper status codes (201, 400, 404, 409) via ProblemDetails, and global exception handling with UseExceptionHandler instead of try/catch in every action.
How to tell it (STAR)
**S:** Our [profile API] used PUT, and when we added a marketing consent field, older app versions started resetting it to false, about [3,000] customers a week. **T:** I needed to stop the data loss, repair affected records and fix the contract so it couldn't recur. **A:** I traced the changes through the audit table and request telemetry to the [v4] user agent, shipped a shim that ignored missing fields on PUT, restored the records from the audit log, then designed a merge-patch endpoint with If-Match concurrency and contract tests that replay old payloads. **R:** Accidental resets dropped to zero within [a day], payloads shrank by [~90%], and the replay tests have since caught [two] other breaking changes before release.
Last updated 23 Nov 2026.