ASP.NET Core support for JSON PATCH. This package was built from the source code at https://github.com/dotnet/dotnet/tree/87bc0b04e21d786669142109a5128c95618b75ed
$ dotnet add package Microsoft.AspNetCore.JsonPatchMicrosoft.AspNetCore.JsonPatch provides ASP.NET Core support for JSON PATCH requests.
To use Microsoft.AspNetCore.JsonPatch, follow these steps:
dotnet add package Microsoft.AspNetCore.JsonPatch
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
To enable JSON Patch support, call AddNewtonsoftJson in your ASP.NET Core app's Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddNewtonsoftJson();
System.Text.JsonTo add support for JSON Patch using Newtonsoft.Json while continuing to use System.Text.Json for other input and output formatters:
Program.cs with logic to construct a NewtonsoftJsonPatchInputFormatter:
static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
{
var builder = new ServiceCollection()
.AddLogging()
.AddMvc()
.AddNewtonsoftJson()
.Services.BuildServiceProvider();
return builder
.GetRequiredService<IOptions<MvcOptions>>()
.Value
.InputFormatters
.OfType<NewtonsoftJsonPatchInputFormatter>()
.First();
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(options =>
{
options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
});
To define an action method for a JSON Patch in an API controller:
HttpPatch attributeJsonPatchDocument<TModel>ApplyTo on the patch document to apply changesFor example:
[HttpPatch]
public IActionResult JsonPatchWithModelState(
[FromBody] JsonPatchDocument<Customer> patchDoc)
{
if (patchDoc is not null)
{
var customer = CreateCustomer();
patchDoc.ApplyTo(customer, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return new ObjectResult(customer);
}
else
{
return BadRequest(ModelState);
}
}
In a real app, the code would retrieve the data from a store such as a database and update the database after applying the patch.
For additional documentation and examples, refer to the official documentation on JSON Patch in ASP.NET Core.
Microsoft.AspNetCore.JsonPatch is released as open-source under the MIT license. Bug reports and contributions are welcome at the GitHub repository.