Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created September 8, 2023 09:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/842bb52479452fe185f58e3885724cac to your computer and use it in GitHub Desktop.
Save dj-nitehawk/842bb52479452fe185f58e3885724cac to your computer and use it in GitHub Desktop.
JsonPatch usage with Swagger UI support
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);
}
}
{
"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