aspnetcore/web-api/jsonpatch.md
:::moniker range=">= aspnetcore-10.0"
This article explains how to handle JSON Patch requests in an ASP.NET Core web API.
JSON Patch support in ASP.NET Core web API is based on xref:System.Text.Json serialization, and requires the Microsoft.AspNetCore.JsonPatch.SystemTextJson NuGet package.
The JSON Patch standard:
Is a standard format for describing changes to apply to a JSON document.
Is defined in RFC 6902 and is widely used in RESTful APIs to perform partial updates to JSON resources.
Describes a sequence of operations that modify a JSON document such as:
addremovereplacemovecopytestIn web apps, JSON Patch is commonly used in a PATCH operation to perform partial updates of a resource. Rather than sending the entire resource for an update, clients can send a JSON Patch document containing only the changes. Patching reduces payload size and improves efficiency.
For an overview of the JSON Patch standard, see jsonpatch.com.
JSON Patch support in ASP.NET Core web API is based on xref:System.Text.Json serialization, starting with .NET 10, implementing xref:Microsoft.AspNetCore.JsonPatch based on xref:System.Text.Json serialization. This feature:
Microsoft.AspNetCore.JsonPatch.SystemTextJson NuGet package.Newtonsoft.Json-based implementation. For more information on the legacy Newtonsoft.Json-based implementation, see the .NET 9 version of this article.[!NOTE] The implementation of xref:Microsoft.AspNetCore.JsonPatch based on xref:System.Text.Json?displayProperty=fullName serialization isn't a drop-in replacement for the legacy
Newtonsoft.Json-based implementation. It doesn't support dynamic types, for example xref:System.Dynamic.ExpandoObject.
[!IMPORTANT] The JSON Patch standard has inherent security risks. Since these risks are inherent to the JSON Patch standard, the ASP.NET Core implementation doesn't attempt to mitigate inherent security risks. It's the responsibility of the developer to ensure that the JSON Patch document is safe to apply to the target object. For more information, see the Mitigating Security Risks section.
To enable JSON Patch support with xref:System.Text.Json, install the Microsoft.AspNetCore.JsonPatch.SystemTextJson NuGet package.
dotnet add package Microsoft.AspNetCore.JsonPatch.SystemTextJson
This package provides a xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument%601 class to represent a JSON Patch document for objects of type T and custom logic for serializing and deserializing JSON Patch documents using xref:System.Text.Json. The key method of the xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument%601 class is xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument.ApplyTo(System.Object), which applies the patch operations to a target object of type T.
In an API controller, an action method for JSON Patch:
:::code language="csharp" source="~/web-api/jsonpatch/samples/10.x/JsonPatchSample/Controllers/CustomerController.cs" id="snippet_PatchAction" highlight="1,2,14-19":::
This code from the sample app works with the following Customer and Order models:
:::code language="csharp" source="~/web-api/jsonpatch/samples/10.x/JsonPatchSample/Models/Customer.cs":::
:::code language="csharp" source="~/web-api/jsonpatch/samples/10.x/JsonPatchSample/Models/Order.cs":::
The sample action method's key steps:
Customer object from the database AppDb using the provided id.Customer object is found, it returns a 404 Not Found response.Customer object.ModelState using the type name of the affected object and the error message.ModelState for errors.ModelState is invalid, such as due to patch errors, it returns a 400 Bad Request response with the validation errors.ModelState is valid, the method returns the updated Customer object in the response.The following example shows the body of a 400 Bad Request response for a JSON Patch operation when the specified path is invalid:
{
"Customer": [
"The target location specified by path segment 'foobar' was not found."
]
}
The following examples demonstrate how to use the xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument.ApplyTo(System.Object) method to apply a JSON Patch document to an object.
The following example demonstrates:
add, replace, and remove operations.// Original object
var person = new Person {
FirstName = "John",
LastName = "Doe",
Email = "[email protected]",
PhoneNumbers = [new() {Number = "123-456-7890", Type = PhoneNumberType.Mobile}],
Address = new Address
{
Street = "123 Main St",
City = "Anytown",
State = "TX"
}
};
// Raw JSON patch document
string jsonPatch = """
[
{ "op": "replace", "path": "/FirstName", "value": "Jane" },
{ "op": "remove", "path": "/Email"},
{ "op": "add", "path": "/Address/ZipCode", "value": "90210" },
{ "op": "add", "path": "/PhoneNumbers/-", "value": { "Number": "987-654-3210",
"Type": "Work" } }
]
""";
// Deserialize the JSON patch document
var patchDoc = JsonSerializer.Deserialize<JsonPatchDocument<Person>>(jsonPatch);
// Apply the JSON patch document
patchDoc!.ApplyTo(person);
// Output updated object
Console.WriteLine(JsonSerializer.Serialize(person, serializerOptions));
The previous example results in the following output of the updated object:
{
"firstName": "Jane",
"lastName": "Doe",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "TX",
"zipCode": "90210"
},
"phoneNumbers": [
{
"number": "123-456-7890",
"type": "Mobile"
},
{
"number": "987-654-3210",
"type": "Work"
}
]
}
The xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument.ApplyTo(System.Object) method generally follows the conventions and options of xref:System.Text.Json for processing the xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument%601, including the behavior controlled by the following options:
Key differences between xref:System.Text.Json and the new xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument%601 implementation:
There are various errors that can occur when applying a JSON Patch document. For example, the target object may not have the specified property, or the value specified might be incompatible with the property type.
JSON Patch supports the test operation, which checks if a specified value equals the target property. If it doesn't, it returns an error.
The following example demonstrates how to handle these errors gracefully.
[!Important] The object passed to the xref:Microsoft.AspNetCore.JsonPatch.SystemTextJson.JsonPatchDocument.ApplyTo(System.Object) method is modified in place. The caller is responsible for discarding changes if any operation fails.
// Original object
var person = new Person {
FirstName = "John",
LastName = "Doe",
Email = "[email protected]"
};
// Raw JSON patch document
string jsonPatch = """
[
{ "op": "replace", "path": "/Email", "value": "[email protected]"},
{ "op": "test", "path": "/FirstName", "value": "Jane" },
{ "op": "replace", "path": "/LastName", "value": "Smith" }
]
""";
// Deserialize the JSON patch document
var patchDoc = JsonSerializer.Deserialize<JsonPatchDocument<Person>>(jsonPatch);
// Apply the JSON patch document, catching any errors
Dictionary<string, string[]>? errors = null;
patchDoc!.ApplyTo(person, jsonPatchError =>
{
errors ??= new ();
var key = jsonPatchError.AffectedObject.GetType().Name;
if (!errors.ContainsKey(key))
{
errors.Add(key, new string[] { });
}
errors[key] = errors[key].Append(jsonPatchError.ErrorMessage).ToArray();
});
if (errors != null)
{
// Print the errors
foreach (var error in errors)
{
Console.WriteLine($"Error in {error.Key}: {string.Join(", ", error.Value)}");
}
}
// Output updated object
Console.WriteLine(JsonSerializer.Serialize(person, serializerOptions));
The previous example results in the following output:
Error in Person: The current value 'John' at path 'FirstName' is not equal
to the test value 'Jane'.
{
"firstName": "John",
"lastName": "Smith", <<< Modified!
"email": "[email protected]", <<< Modified!
"phoneNumbers": []
}
When using the Microsoft.AspNetCore.JsonPatch.SystemTextJson package, it's critical to understand and mitigate potential security risks. The following sections outline the identified security risks associated with JSON Patch and provide recommended mitigations to ensure secure usage of the package.
[!IMPORTANT] This is not an exhaustive list of threats. App developers must conduct their own threat model reviews to determine an app-specific comprehensive list and come up with appropriate mitigations as needed. For example, apps which expose collections to patch operations should consider the potential for algorithmic complexity attacks if those operations insert or remove elements at the beginning of the collection.
To minimize security risks when integrating JSON Patch functionality into their apps, developers should:
copy operation that duplicates large object graphs multiple times, leading to excessive memory consumption.public void Validate(JsonPatchDocument<T> patch)
{
// This is just an example. It's up to the developer to make sure that
// this case is handled properly, based on the app needs.
if (patch.Operations.Where(op=>op.OperationType == OperationType.Copy).Count()
> MaxCopyOperationsCount)
{
throw new InvalidOperationException();
}
}
View or download sample code. (How to download).
To test the sample, run the app and send HTTP requests with the following settings:
http://localhost:{port}/jsonpatch/jsonpatchwithmodelstatePATCHContent-Type: application/json-patch+json:::moniker-end