Last active
October 9, 2025 13:22
-
-
Save dj-nitehawk/842bb52479452fe185f58e3885724cac to your computer and use it in GitHub Desktop.
JsonPatch usage with Swagger UI support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.AspNetCore.JsonPatch; | |
| using Microsoft.AspNetCore.JsonPatch.Operations; | |
| using Newtonsoft.Json; | |
| using Newtonsoft.Json.Serialization; | |
| using Serializer = System.Text.Json.JsonSerializer; | |
| var bld = WebApplication.CreateBuilder(); | |
| bld.Services | |
| .AddAuthorization() | |
| .AddFastEndpoints() | |
| .SwaggerDocument(); | |
| var app = bld.Build(); | |
| app.UseAuthorization() | |
| .UseFastEndpoints() | |
| .UseSwaggerGen(); | |
| app.Run(); | |
| abstract class PatchRequest | |
| { | |
| [FromBody] | |
| public List<Operation> Patches { get; set; } | |
| internal void Patch(object model) | |
| => new JsonPatchDocument( | |
| operations: Patches.Select(o => JsonConvert.DeserializeObject<Operation>(Serializer.Serialize(o))).ToList(), | |
| contractResolver: new DefaultContractResolver()) | |
| .ApplyTo(model); | |
| } | |
| sealed class UpdateUserRequest : PatchRequest | |
| { | |
| public int UserId { get; set; } | |
| } | |
| sealed class Person | |
| { | |
| public string FirstName { get; set; } | |
| public string LastName { get; set; } | |
| } | |
| sealed class UpdatePersonEndpoint : Endpoint<UpdateUserRequest> | |
| { | |
| public override void Configure() | |
| { | |
| Patch("test/{UserId}"); | |
| Description(b => b.Accepts<UpdateUserRequest>("application/json-patch+json")); | |
| AllowAnonymous(); | |
| } | |
| public override async Task HandleAsync(UpdateUserRequest req, CancellationToken ct) | |
| { | |
| var user = new Person { FirstName = "first", LastName = "last" }; | |
| req.Patch(user); | |
| await Send.OkAsync(user); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [ | |
| { | |
| "path": "/firstName", | |
| "op": "replace", | |
| "value": "Fast" | |
| }, | |
| { | |
| "path": "/lastName", | |
| "op": "replace", | |
| "value": "Endpoints" | |
| } | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment