Created
September 8, 2023 09:06
-
-
Save dj-nitehawk/842bb52479452fe185f58e3885724cac to your computer and use it in GitHub Desktop.
JsonPatch usage with Swagger UI support
This file contains 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 FastEndpoints.Swagger; | |
using Microsoft.AspNetCore.JsonPatch; | |
using Microsoft.AspNetCore.JsonPatch.Operations; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
using NJsonSchema.Annotations; | |
using System.Text.Json; | |
var bld = WebApplication.CreateBuilder(); | |
bld.Services | |
.AddAuthorization() | |
.AddFastEndpoints() | |
.SwaggerDocument(); | |
var app = bld.Build(); | |
app.UseAuthorization() | |
.UseFastEndpoints() | |
.UseSwaggerGen(); | |
app.Run(); | |
public abstract class PatchRequest | |
{ | |
[JsonSchemaType(typeof(Operation[]))] | |
public JsonElement[] Patches { get; set; } | |
public void Patch<TModel>(TModel model) where TModel : class | |
{ | |
var doc = new JsonPatchDocument( | |
operations: Patches.Select(o => JsonConvert.DeserializeObject<Operation>(o.GetRawText())).ToList(), | |
contractResolver: new DefaultContractResolver()); | |
doc.ApplyTo(model); | |
} | |
} | |
public class UpdateUserRequest : PatchRequest | |
{ | |
public int UserID { get; set; } | |
} | |
public class Person | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
} | |
public class UpdatePersonEndpoint : Endpoint<UpdateUserRequest> | |
{ | |
public override void Configure() | |
{ | |
Patch("test/{UserID}"); | |
AllowAnonymous(); | |
} | |
public override async Task HandleAsync(UpdateUserRequest req, CancellationToken ct) | |
{ | |
var user = new Person { FirstName = "first", LastName = "last" }; | |
req.Patch(user); | |
await SendAsync(user); | |
} | |
} |
This file contains 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
{ | |
"patches": [ | |
{ | |
"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