Repository navigation
Description
Track the design and implementation of C# union type support in Minimal APIs non-body parameter binding sources: query string, route values, headers, and form fields. Body parameters are covered in related issues (#66542, #66543) because STJ does the heavy lifting; non-body bindings go through a completely different pipeline (TryParse / IParsable<T> / form complex-type binding) and need their own design.
Scenarios
**Union from query string (simple cases):
union Sort(Ascending, Descending);
app.MapGet("/items", ([FromQuery] Sort sort) => /* ... */);
// GET /items?sort=ascendingUnion from route value:
union Id(int Numeric, Guid Guid);
app.MapGet("/items/{id}", (Id id) => /* ... */);
// /items/42 → Numeric(42)
// /items/3fa85f64-5717-4562-b3fc-2c963f66afa6 → Guid(...)Union from form (complex):
union Command(CreateOrder, UpdateOrder);
// CreateOrder { int CustomerId, string[] Items }
// UpdateOrder { int OrderId, string Status }
app.MapPost("/orders", ([FromForm] Command command) => /* ... */);
// content-type: application/x-www-form-urlencoded
// body: customerId=42&items=apple&items=pear → binds CreateOrder
// body: orderId=7&status=shipped → binds UpdateOrderUnion from header:
union AuthScheme(BearerToken, ApiKey);
app.MapGet("/secure", ([FromHeader] AuthScheme auth) => /* ... */);Areas to investigate / design questions
-
Parameter classification (
RequestDelegateFactory.CreateArgument,EndpointParameterin RDG):- Today: union types with no
TryParseand no explicit[FromQuery]/[FromRoute]/[FromForm]are inferred as body parameters. - We need to decide how an explicitly-attributed union (
[FromQuery] MyUnion x) is bound.
- Today: union types with no
-
TryParsesemantics for unions — design choices:- Option A (compiler-synthesized): If C# emits a
TryParseon unions whose cases are allIParsable<T>, RDF/RDG just uses it — no ASP.NET work beyond detection. - Option B (framework-side fallback): ASP.NET tries each case's
TryParsein declaration order, picks the first success. Ambiguity rules + classifier hooks needed. - Option C (require explicit format): Force users to provide an
IParsable<TUnion>implementation. No magic. - Need to align with the C# language design — confirm whether unions get auto-generated
TryParse/IParsable<T>for parsable cases.
- Option A (compiler-synthesized): If C# emits a
-
Complex form binding (
FormDataMapper/ RDG form emitter):FormDataMapperwalks properties of complex form-bound types. For unions it needs to determine the active case and recurse into its properties.- Non-discriminator (structural) matching must be supported as the default path, mirroring STJ's behavior for unambiguous unions: pick the case whose required-property set matches the posted form fields. Example —
union Command(CreateOrder { CustomerId, Items }, UpdateOrder { OrderId, Status })should bindcustomerId=...&items=...toCreateOrderwithout anykind=field. - Discriminator-based matching is an opt-in for ambiguous unions (e.g., two cases share the same property shape) and should follow the same classifier convention used by STJ — not a separate ASP.NET-only concept.
- Ambiguity / no-match handling: define clear errors when zero or multiple cases match.
-
Unambiguous primitive unions — should
union Sort(Ascending, Descending)(case-class unions with no payload) bind from?sort=ascendingautomatically? This is a strong UX win and probably the most-requested scenario. No discriminator needed — the value itself names the case. -
Value-shape unions in query/route/header —
union Id(int Numeric, Guid Guid)should bind by trying each case's parser; first unambiguous success wins. No discriminator field — the input shape itself disambiguates. Only fall back to a discriminator/classifier when case parsers overlap (e.g.,union(int, long)). -
Error reporting:
- 400 responses should clearly indicate which union case failed to parse (or that no case matched / multiple cases matched), not a generic "invalid value".
- Decide on the
BadRequestpayload format (especially for forms with multiple invalid fields).
-
OpenAPI implications:
- Query/route parameters of union type need schema representation distinct from body schemas covered in OpenAPI: Generate anyOf schemas for C# union types #66544.
- OpenAPI 3.0 parameters don't support
anyOfcleanly at the parameter level — likely need to expand to multiple parameter definitions or document a singlestringparameter with format hints. Coordinate with OpenAPI: Generate anyOf schemas for C# union types #66544.
-
RDG parity (Minimal APIs (RDG): Source-generated support for union types #66543 sibling):
- Whatever runtime contract we land on must be detectable at compile time by the source generator.
IsParsable/IsBindablechecks in RDG need to recognize unions.
Activity
github-actions commentedon May 11, 2026
Triage Summary
Area:
area-minimal— tracks design/implementation of C# union type support in Minimal APIs non-body parameter binding (query string, route, headers, form) viaRequestDelegateFactory,EndpointParameter,FormDataMapper, and the Request Delegate Generator (RDG).Type:
feature-request— requests new functionality: binding C# union types from non-body sources, which is not currently implemented.Potential Duplicates
No exact duplicates found for the non-body parameter binding scenario.
Notes
area-minimalandfeature-requestlabels — no label changes needed.FormDataMapper.Youssef1313 commentedon May 13, 2026
Putting to backlog. We would like to hear more feedback from users about the scenarios before adding the support.
[-]Support C# unions types in non-body parameter binding[/-]PaulusParssinen commentedon May 14, 2026
Hoping this will make it apparent that there is need to provide extension point in Minimal APIs for binding errors (#35501)
Focus on where unions aren't supported; revert affirmative inserts
Drop redirect, DynamicComponent note, parameter-binding.md date, and …
Retire standalone C# unions article; document where unions aren't sup…
robertodalmonte commentedon Sep 11, 2026
Feedback from RC 1 (
11.0.0-rc.1.26425.128) on how non-body union parameters behave today, ahead of the design here. Two of these outcomes are silent. They seem worth fixing whether or not union binding lands, because they affect code that compiles today.union IntOrString(int, string))[FromQuery],[FromHeader]ASP0020(an error by default)?v=42binds as thestringcase"42"[FromForm]ASP0020; RDG emits onlyRDG003and falls back to RDFdefault(IntOrString)(Value == null)[FromQuery]/[FromHeader]/[FromForm]ComplexObjectModelBinder: "Could not create an instance of type 'IntOrString'…"For a union without a
stringcase, the RDG path does not compile at all:That comes from the emitted binding code, which relies on the union conversion from
string:Repros. Each is a separate app, for the reasons given below. For the RDG results, build with
-p:EnableRequestDelegateGenerator=true --no-incremental.1. Form (RDF and RDG give the same result):
2. Query, with
dotnet_diagnostic.ASP0020.severity = nonein.editorconfig:3.
CS0029, which stops the RDG build:Keep the repros in separate apps. On the RDF path, the query endpoint's build failure makes every route in the host return 500,
/formincluded. That part is ordinary Minimal API behaviour for any endpoint that fails to build, not a union issue.Two asks that don't depend on the binding design:
[FromForm]union parameters the way query, route and header already are, withASP0020or a union-specific diagnostic. Today form binding succeeds silently with a null-valued union, which is the one union state that noswitchcan see coming (a missingnullarm draws no warning).[FromForm](RDG003), instead of emitting thestring→ union conversion. That conversion either binds the wrong case silently or produces generated code that doesn't compile, and in both cases RDG diverges from RDF.Environment: .NET SDK
11.0.100-rc.1.26425.128,Microsoft.AspNetCore.App11.0.0-rc.1.26425.128, Windows 11 x64.DeagleGross commentedon Sep 14, 2026
@robertodalmonte thanks for your input - there will not be support for unions in parameter binding in NET11, but we are considering improving in the area in NET12.
Is there any concrete world-scenario you want to achieve with union usage in headers/query/forms? Or that's more an academic interest? Let us know please!
Also given there is no output from the framework I am checking if we could add the analyzer to report a warning if you try to use it. Will that help make the union usage be more transparent?
robertodalmonte commentedon Sep 15, 2026
Thanks. On the scenario question: no production endpoint of mine is blocked on this. I found these while documenting how C# 15 unions behave across the ASP.NET Core stack before adopting them. Everything below is RC 1 (11.0.100-rc.1.26425.128), reflection, and RDG builds; the generated file was checked.
Re-testing changed what I'd ask for:
Non-body binding already works if the union implements IParsable (public union IntOrString(int, string) : IParsable { … }). It binds correctly from query, header, route, and form on Minimal API (RequestDelegateFactory and RDG, which reports IsParsable = True) and on MVC [ApiController], and ASP0020 does not fire. So ASP0020's guidance is right as it stands, and I don't think query/header/route needs union-specific binding in .NET 12; which case wins for an input both cases accept is application policy, and the union's own TryParse is where it belongs.
The one genuinely silent case is [FromForm], and it isn't union code. A plain struct with one constructor (struct Opaque1 { Opaque1(int value); }) binds value=42 by parameter name. A struct with two single-argument constructors (Opaque2(int value) / Opaque2(string value)) binds the default with 200 for every key. A C# 15 union lowers to that shape and inherits it, so the handler receives a union with Value == null and no diagnostic—RDG emits RDG003 and falls back to reflection, which gives the same result.
The fix I'd ask for is in form binding rather than a union analyzer: refuse a type the mapper can't construct, the way RequestDelegateFactory already throws "must have a valid TryParse" for a non-parsable query parameter. That covers Opaque2 as well. If an analyzer is the practical route for 11, then: cover [FromForm], exempt types implementing IParsable, and default to ASP0020's severity, since the outcome is an uninitialised value reaching the handler.
Minor: with ASP0020 suppressed, RDG and RequestDelegateFactory disagree on the same [FromQuery] union. RDG assigns the raw string through the union's compiler-generated implicit conversion (200 with the string case, or CS0029 in generated code if there is no string case); RequestDelegateFactory returns 500.
Repro: https://github.com/robertodalmonte/csharp-unions-probed/tree/main/probes/QParsable (
dotnet run; RDG build command in probes/README.md). The RDG/RequestDelegateFactory disagreement is in probes/RdgNoString and probes/QRepro2.DeagleGross commentedon Sep 15, 2026
Thanks for response @robertodalmonte,
Can you please another issue and describe what you expect there? It's a general behavior not directly related to union, so we can discuss it separately.
Regarding the analyzer - we are not sure this will be included in net11 given too late in the release. We'll see what we decide to do for net12. Documentation already describes that header/query/form does not have special support for unions, so it is up to user to verify the correct behavior
robertodalmonte commentedon Sep 15, 2026
Done: #69322 covers the form-binding behaviour on its own, with no union in the repro. It links #51379, which hits the same path from the other direction.
Understood on the analyzer and the docs note. I'll keep verifying against RC 2 and GA.