Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created July 31, 2024 06:40
Show Gist options
  • Save dj-nitehawk/8a938ac7edb1ac840ed0601121d557ea to your computer and use it in GitHub Desktop.
Save dj-nitehawk/8a938ac7edb1ac840ed0601121d557ea to your computer and use it in GitHub Desktop.
Using OneOf for polymorphic schema
using System.Text.Json.Serialization;
var bld = WebApplication.CreateBuilder(args);
bld.Services
.SwaggerDocument(o => o.UseOneOfForPolymorphism = true) //enable the setting
.AddFastEndpoints();
var app = bld.Build();
app.UseFastEndpoints()
.UseSwaggerGen();
app.Run();
public class Apple : Fruit
{
public string Foo { get; set; }
}
public class Orange : Fruit
{
public string Bar { get; set; }
}
[
JsonPolymorphic(TypeDiscriminatorPropertyName = "_t"),
JsonDerivedType(typeof(Apple), "a"),
JsonDerivedType(typeof(Orange), "o")
]
public class Fruit
{
public string Baz { get; set; }
}
sealed class MyEndpoint : Endpoint<Fruit>
{
public override void Configure()
{
Post("/api/fruit");
AllowAnonymous();
}
public override async Task HandleAsync(Fruit r, CancellationToken c)
{
await SendAsync(r as Apple);
}
}
@dj-nitehawk
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment