With .NET 10 Preview 4 onwards, you can now use JsonPatch with System.Text.Json in ASP.NET Web API.
Currently if you need to use JsonPatch you need to rely on Newtonsoft.Json as described in this article: JsonPatch in ASP.NET Core web API
Note: this isn't a complete drop-in replacement for the existing Newtonsoft.Json based implementation. In particular, the new implementation doesn't support dynamic types (like ExpandoObject).
Now let's see how this works.
First you need to install a new package, Microsoft.AspNetCore.JsonPatch.SystemTextJson. Note: it's still prerelease.
dotnet add package Microsoft.AspNetCore.JsonPatch.SystemTextJson --prerelease
Next, we can use the JsonPatchDocument<TModel>, that is introduced in Microsoft.AspNetCore.JsonPatch.SystemTextJson.
using Microsoft.AspNetCore.JsonPatch.SystemTextJson;using Microsoft.AspNetCore.Mvc;namespace WebApplication1.Controllers;[ApiController][Route("[controller]")]public class EmployeesController : ControllerBase{[HttpPatch][Route("{employeeId}")]public Employee PatchEmployee([FromRoute] int employeeId,JsonPatchDocument<Employee> patchDocument){Employee employee = new(){Id = employeeId,FirstName = "John",LastName = "Doe",Address = new Employee.AddressDto{Street = "123 Main St",City = "Redmond",State = "WA",ZipCode = "12345"}};patchDocument.ApplyTo(employee);return employee;}}
You don't have to do any changes to the Program.cs.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
WebApplication app = builder.Build();
app.MapControllers();
app.Run();
And invoke the endpoint like follows.
@WebApplication1_HostAddress = https://localhost:7070PATCH {{WebApplication1_HostAddress}}/employees/1Content-Type: application/json[{"op": "replace","path": "/LastName","value": "Bloggs"},{"op": "replace","path": "/Address/ZipCode","value": "90100"}]
Happy Coding.
No comments:
Post a Comment