A typical endpoint has several ways to end: it worked, the thing was missing, the input was bad. Most code expresses that with exceptions, or with a handler that returns an untyped IResult and hopes every branch picked the right status. Nothing tells the compiler which outcomes exist, so nothing can tell you when you forgot one.
.NET 11 ships C# 15 as the default language version for net11.0, and C# 15 adds a union declaration. I built a small fee calculator API where every endpoint returns a closed list of outcomes, and the compiler checks that each outcome is turned into an HTTP status. A forgotten case fails the build instead of reaching production.
🧪 Synthetic data only. Findings are from .NET SDK 11.0.100 and Microsoft.AspNetCore.OpenApi 11.0.0. The union compiled with no preview switch.
Full code:
arbabazmi / dotnet11-web-samples
ASP.NET Core 11 sample projects: C# 15 unions, MCP + Blazor AI, Native AOT benchmark
.NET 11 Web Samples
Three small ASP.NET Core 11 projects that try what is new on the web side of .NET 11, and write down what worked, what surprised me and what did not. All data is synthetic. Everything here was built and run on .NET SDK 11.0.100.
| # | Project | Folder | What it shows |
|---|---|---|---|
| 1 | Fee calculator API | src/FeeCalc.Api | C# 15 union types, mapped to HTTP with exhaustive switch |
| 2 | MCP server + Blazor AI chat | src/CommissionMcp.Server, src/CommissionMcp.Web | An MCP server, and a chat page where a model calls its tools and a person approves any change |
| 3 | Native AOT benchmark | src/Aot.Bench | Cold start, memory and image size: JIT vs Native AOT on .NET 10 and .NET 11 |
Each project folder has its own README with the details, commands and findings. This page is the overview.
Prerequisites
| Needed for | Install |
|---|---|
| Everything | .NET SDK 11.0.100 (pinned in global.json) |
| Project |
Before and after
Before (an illustration of the common pattern, not code from the repo): untyped, any status can slip through.
app.MapPost("/fees/calculate", async (FeeRequest r, FeeService svc) => { var card = await svc.GetCard(r.Tier); if (card is null) return Results.NotFound(); // 404? if (r.Amount <= 0) return Results.BadRequest(); // 400 or 422? return Results.Ok(svc.Calc(card, r)); // nothing checks the list }); After: a closed list the compiler enforces.
public union CalcResult( Calculated, RateNotFound, ValidationFailed); // handler (await svc.CalculateAsync(r, ct)).ToHttp() // ^ one switch maps every case, or the build fails A union is a value that is exactly one of a fixed set of types. The runtime includes the UnionAttribute and IUnion types it relies on.
The design in one picture
Two endpoints, two unions. Each case is a small record, and each case has exactly one HTTP status. The kind property on every case is there for clients: a union serialises as just the case that was picked, with no marker of which one. Without kind, a client could only tell cases apart by the status code.
The key code
1. Declare the unions (Domain/Types.cs)
public record Calculated(decimal Fee, decimal RateBps, string Tier, AccountType AccountType) { [JsonPropertyName("kind")] public string Kind => "calculated"; } public record RateNotFound(string Tier, AccountType AccountType) { /* kind = "rate_not_found" */ } public record ValidationFailed(IReadOnlyList<ValidationError> Errors) { /* kind = "validation_failed" */ } public union CalcResult(Calculated, RateNotFound, ValidationFailed); public union RateResult(RateCard, NotFound); Each case is an ordinary record. A case converts to the union implicitly, so a method declared to return CalcResult can simply return new RateNotFound(...).
2. Return a case instead of throwing (Domain/FeeService.cs)
public async Task<CalcResult> CalculateAsync(FeeRequest request, CancellationToken ct = default) { var card = await rates.GetAsync(request.Tier, ct); if (card is null || !card.RatesBps.TryGetValue(request.AccountType, out var bps)) return new RateNotFound(request.Tier, request.AccountType); var fee = Math.Round(request.Amount * bps / 10_000m, 2, MidpointRounding.AwayFromZero); return new Calculated(fee, bps, card.Tier, request.AccountType); } Rates are in basis points, so bps / 10,000 turns 50 into 0.50%. The method's return type now documents every way it can end.
3. Map every case to a status (Http/UnionHttpMapping.cs)
public static IResult ToHttp(this CalcResult result) => result switch { Calculated c => Results.Ok(c), // 200 RateNotFound n => Results.NotFound(n), // 404 ValidationFailed v => Results.UnprocessableEntity(v), // 422 }; There is no default arm, on purpose. A default would swallow new cases silently. Without one, the compiler can check that every case is covered.
4. Validate asynchronously, then run the handler (Program.cs)
fees.MapPost("/calculate", async (FeeRequest request, FeeService svc, CancellationToken ct) => (await svc.CalculateAsync(request, ct)).ToHttp()) .AddEndpointFilter(async (ctx, next) => { var request = ctx.GetArgument<FeeRequest>(0); var validator = ctx.HttpContext.RequestServices.GetRequiredService<IAsyncValidator<FeeRequest>>(); var errors = await validator.ValidateAsync(request, ctx.HttpContext.RequestAborted); return errors.Count > 0 ? ((CalcResult)new ValidationFailed(errors)).ToHttp() // handler never runs : await next(ctx); }) .Produces<Calculated>(StatusCodes.Status200OK) .Produces<RateNotFound>(StatusCodes.Status404NotFound) .Produces<ValidationFailed>(StatusCodes.Status422UnprocessableEntity); The filter runs before the handler and awaits the rate table to check the tier. When it finds errors it builds a ValidationFailed case and sends it through the same ToHttp() mapping, so validation errors and business outcomes share one path.
⚠️ Detail to know about. The filter reads the request with
GetArgument<FeeRequest>(0), the handler's first parameter. Reordering the handler's parameters would break it without a compile error. This validator is hand-written for clarity; .NET 11 also describes built-in async validation, which this project does not use.
Break it on purpose
This is the part the article exists for. Delete one arm of the switch and build:
By default a missing case is only a warning (CS8509), and a warning is easy to ignore. One line in the project file turns it into an error:
<WarningsAsErrors>CS8509</WarningsAsErrors> The message for a missing ValidationFailed was captured from a real build. When several arms are missing, the compiler names one example.
Requests, recorded from the running API
| Request | Status | Case | What happened |
|---|---|---|---|
POST /fees/calculate gold, Brokerage, 10,000 | 200 | Calculated | Gold pays 50 bps on Brokerage, so the fee is 50 |
POST /fees/calculate silver, Advisory, 100 | 404 | RateNotFound | Silver exists, so validation passes, but it has no Advisory rate |
POST /fees/calculate platinum, amount -1 | 422 | ValidationFailed | The filter finds two errors; the handler never runs |
GET /fees/rates/gold | 200 | RateCard | No filter on this endpoint; the service finds the card |
GET /fees/rates/nope | 404 | NotFound | No such tier; the switch turns it into 404 |
The 422 response, for example:
{"errors":[{"field":"amount","message":"Amount must be greater than zero."},{"field":"tier","message":"Tier 'platinum' does not exist."}],"kind":"validation_failed"} Two ways to get "not found". An unknown tier such as platinum never reaches the service: the validation filter catches it and returns 422. A tier that exists but has no rate for the account type passes validation, and the service returns RateNotFound, which becomes 404.
What the OpenAPI document shows
The app generates OpenAPI 3.2 at /openapi/v1.json, and every union case appears as a response schema for its operation: 200/404/422 for POST /fees/calculate, 200/404 for GET /fees/rates/{tier}.
Gaps worth recording:
- Handlers return
IResultafterToHttp(), so the generator cannot see the union. The cases appear only because of theProduceslines. The union types themselves are not incomponents/schemas. - In an early spike, returning a union straight from a handler produced one schema with
anyOfover the cases and only a 200 response. That is why this project declares each status explicitly. - Also in that spike, a
decimalwas described as["number","string"]withformat: double.
What worked, what surprised me, what did not
✅ Worked
- The union syntax compiled on SDK 11.0.100 without any preview flag.
- Exhaustive switches over a union catch a missing case at compile time.
- One mapping function keeps status codes in a single file.
- OpenAPI 3.2 output with every case listed per operation.
🤔 Surprised me
- A missing case is only a warning (CS8509) until you promote it to an error.
- A union serialises as the bare case, with no marker of which case it is.
- Two different "not found" paths (filter or service) for one endpoint.
❌ Did not work
- Relying on the OpenAPI generator to read the union. It needed explicit
Producesdeclarations. - Leaving the cases without a discriminator. Clients need
kind.
The numbers
- 15 tests passing (unit, mapping, endpoint)
- 5 union cases, each with one status
- 2 endpoints, 2 unions
- 3.2 OpenAPI version emitted
Unit tests cover each union case and each mapping arm. Integration tests use WebApplicationFactory to call each endpoint, including the OpenAPI document.
Run it yourself
Requires the .NET 11 SDK (tested on 11.0.100). Code is in src/FeeCalc.Api.
git clone https://github.com/arbabazmi/dotnet11-web-samples cd dotnet11-web-samples dotnet test dotnet run --project src/FeeCalc.Api --urls http://localhost:5199 # then open http://localhost:5199/openapi/v1.json Would you replace exceptions with unions in your APIs, or keep them for truly exceptional cases? I'd like to hear in the comments.
Synthetic data only. Findings are from .NET SDK 11.0.100 and Microsoft.AspNetCore.OpenApi 11.0.0.


