Debugging question on a wrong or incomplete OpenAPI document in ASP.NET Core: endpoints missing from API Explorer, untyped IResult responses, JsonPolymorphic and JsonDerivedType for oneOf, enum converters, nullable and required properties, and a snapshot test to keep it right.
I treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:
ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.IResult; switch to TypedResults with Results<...>.[JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.JsonStringEnumConverter for the API.required.Then I add a snapshot test of the document. The trade-off: fixing the source (types, JSON options) is more work than patching with transformers, but keeps the docs and the wire format in step.
"The first thing I remember is that the generator doesn't read my code; it reads two things: endpoint metadata through API Explorer, and the System.Text.Json contract for each type. So every wrong thing in the document is either missing metadata or a JSON contract that differs from what I assumed. I start by fetching
/openapi/v1.jsonand, in a quick test, listingIApiDescriptionGroupCollectionProviderdescriptions. If an endpoint isn't in API Explorer, it's a metadata problem; if it is but the schema looks wrong, it's a contract problem.For missing endpoints the usual causes are:
ExcludeFromDescriptionor[ApiExplorerSettings(IgnoreApi = true)]; controllers using conventional routes, which API Explorer ignores, so they need attribute routing; endpoints mapped with plainMapand no HTTP method; Swashbuckle withoutAddEndpointsApiExplorer; or, with several documents, aShouldIncludethat filters by group name. For responses with no schema, it's nearly always a handler returningIResult, so I switch toResults<Ok<T>, NotFound>withTypedResults.Polymorphism, enums and nullability are contract issues. A base type only shows its own properties unless it has
[JsonPolymorphic]and[JsonDerivedType], and then the document gets aoneOfwith a discriminator, which also means the serialiser actually writes the derived properties. Enums come out as integers because that's what System.Text.Json sends; I registerJsonStringEnumConverterthroughConfigureHttpJsonOptionsor on the enum type, and the document and the wire format change together. Nullability follows nullable reference annotations, so a project without<Nullable>enable</Nullable>documents every reference as nullable, andrequiredcomes from therequiredkeyword or[Required]. The mistake I see is fixing the document with a transformer so it says strings while the API still sends integers. Fix the contract, not the description of it."
| Symptom | Likely cause | Fix |
|---|---|---|
| Endpoint missing | ExcludeFromDescription, IgnoreApi, conventional MVC route, no HTTP method, ShouldInclude filter, no AddEndpointsApiExplorer with Swashbuckle |
Remove the exclusion, use attribute routing, map with MapGet/MapPost, fix the filter |
| 200 with no schema | Handler returns IResult |
TypedResults + Results<...>, or Produces<T>() |
| Error responses missing | Produced by filters or middleware | ProducesProblem, ProducesValidationProblem |
| Only base class shown | No polymorphism metadata | [JsonPolymorphic] + [JsonDerivedType] |
| Enums as integers | Default System.Text.Json behaviour | JsonStringEnumConverter in ConfigureHttpJsonOptions or on the enum |
| Everything nullable | Nullable reference types disabled | <Nullable>enable</Nullable>, correct annotations |
| Nothing required | No required/[Required] and no constructor parameters |
required members or positional records |
| Document differs from runtime JSON | Controllers configured with AddJsonOptions but the generator reads a different options instance |
Configure both, or put converters on the types |
| Step | Tool |
|---|---|
| 1. See what the generator sees | /openapi/v1.json, jq, a viewer |
| 2. Is the endpoint in metadata? | API Explorer test, EndpointDataSource |
| 3. What does the wire really look like? | Call the endpoint, compare JSON with the schema |
| 4. Fix the source | Types, JSON options, metadata |
| 5. Lock it in | Snapshot test of the document |
A partner reported that our PaymentMethod responses had properties the document didn't mention. The base record had no [JsonDerivedType], so the document showed only id and type, and their generated client discarded cardLast4 and bsb. Adding the polymorphism attributes produced a oneOf with a kind discriminator, and a snapshot test now fails if the document changes unexpectedly.
Checks that the candidate can trace document problems back to metadata or the JSON contract rather than patching the output.
Green flags
[JsonPolymorphic]/[JsonDerivedType] and that they change serialisation too.Red flags
Endpoint metadata ---> API Explorer ---> paths, operations, parameters, response types
|
System.Text.Json ---> JsonTypeInfo ----------> schemas (properties, types, nullability,
options + attributes required, enums, polymorphism)
|
transformers -> document
If you understand which input owns a symptom, the fix is obvious. Transformers are the last resort, for things neither input can express.
MapControllerRoute) aren't described by API Explorer; [ApiController] requires attribute routing for this reason.app.Map("/x", ...) have no HttpMethodMetadata, so they can't be described as an operation.ExcludeFromDescription(), [ApiExplorerSettings(IgnoreApi = true)], or [ExcludeFromDescription].ShouldInclude matches the endpoint's group name to the document name; an endpoint in group v2 won't appear in v1.IsDevelopment() vanish from a build-time document.[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Card), "card")]
[JsonDerivedType(typeof(BankAccount), "bank")]
public abstract record PaymentMethod(Guid Id);
The built-in generator turns this into oneOf: [Card, BankAccount] with discriminator.propertyName: kind. Without the attributes, System.Text.Json serialises by the declared type, so for a PaymentMethod-typed property the derived properties are not even sent, which is a data bug, not just a docs bug.
JsonStringEnumConverter (or the generic JsonStringEnumConverter<TEnum>, which is AOT-safe) changes both the wire format and the schema to type: string, enum: [...].string? becomes type: ["string", "null"] in OpenAPI 3.1 and string doesn't. required in the schema comes from C# required members, [Required], [JsonRequired] or constructor parameters of records.Fetch the document in a WebApplicationFactory test and compare it with an approved file (Verify, or a plain file compare). Any change shows as a diff that must be accepted deliberately. Pair it with the committed build-time spec for CI checks.
app.Map and one with app.MapGet; check which appears in the document.Results.Ok(dto) and TypedResults.Ok(dto) from two handlers and compare their responses.[JsonDerivedType]; compare both the document and the actual JSON.<Nullable> and diff the schemas./openapi/v1.json.Fixing the sources, not patching the document.
// Program.cs
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
// Enums as strings on the wire AND in the document (Minimal APIs read these options)
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
// MapGet (not Map) so the endpoint has an HTTP method and is described
app.MapGet("/customers/{id:guid}/payment-methods", GetPaymentMethods)
.WithName("GetPaymentMethods")
.ProducesProblem(StatusCodes.Status403Forbidden); // produced by authorisation, not the handler
app.Run();
// Typed results: 200 + schema and 404 documented without Produces
static Results<Ok<PaymentMethod[]>, NotFound> GetPaymentMethods(Guid id) =>
id == Guid.Empty
? TypedResults.NotFound()
: TypedResults.Ok<PaymentMethod[]>([new Card(Guid.NewGuid(), "4242", CardBrand.Visa)]);
// Polymorphism: oneOf with a discriminator, and derived properties are actually serialised
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Card), "card")]
[JsonDerivedType(typeof(BankAccount), "bank")]
public abstract record PaymentMethod(Guid Id);
public sealed record Card(Guid Id, string Last4, CardBrand Brand) : PaymentMethod(Id);
public sealed record BankAccount(Guid Id, string Bsb, string AccountLast3, string? Nickname) : PaymentMethod(Id); // Nickname nullable, others required
public enum CardBrand { Visa, Mastercard, Amex }
// Tests/OpenApiSnapshotTests.cs: any change to the document must be approved
using Microsoft.AspNetCore.Mvc.Testing;
namespace Payments.Api.Tests;
public sealed class OpenApiSnapshotTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task Document_matches_approved_snapshot()
{
var client = factory.CreateClient();
var json = await client.GetStringAsync("/openapi/v1.json", TestContext.Current.CancellationToken);
await VerifyJson(json); // Verify.Xunit: writes *.received.json on mismatch
}
}
IResult and wondering why the schema is empty. Why it is wrong: There is no type information to describe. Instead: TypedResults with Results<...>.[JsonDerivedType], System.Text.Json doesn't serialise them either. Instead: Add polymorphism attributes and test the actual JSON.AddControllers().AddJsonOptions(...) when the document is built from another options instance. Why it is wrong: The document and the runtime output can disagree. Instead: Configure both, or put [JsonConverter] on the type itself.required or positional records.A wrong OpenAPI document is usually a symptom of a real contract problem: an API that sends integers clients don't expect, derived properties that never leave the server, or nullability nobody decided. The senior move is to fix the source and make the document trustworthy enough that clients are generated from it, then guard it with a snapshot test so regressions show up in review.
Two things a senior adds. First, the client impact: generators trust the document, so an undocumented property is silently discarded, a missing schema becomes any, and a wrongly non-nullable field crashes a strongly typed client the first time it is null. That makes document accuracy a data-integrity concern, not cosmetics. Second, the fix itself can break consumers: switching enums to strings or adding a discriminator changes the wire format. Treat it like any contract change: agree it with consumers, ship it in a new version (or behind a compatible addition), and let the breaking-change check in CI make the decision visible. Consistent design rules (one error shape via ProblemDetails, one enum style, explicit nullability, discriminated hierarchies) make the document accurate almost automatically, because there are fewer special cases to describe.
| Fix location | When it fits | Cost | When not to |
|---|---|---|---|
Types (attributes, required, NRT) |
Contract issues: polymorphism, nullability, enums | Touches DTOs | Third-party types you don't own |
| JSON options | App-wide wire-format choices | Changes every response, may be breaking | One-off exceptions |
| Endpoint metadata | Missing endpoints or responses | A few lines per endpoint | Contract shape problems |
| Schema transformer | Formats, examples, third-party types | Can drift from the wire | Anything the serialiser can express |
| New API version | The fix changes the wire format for existing clients | Two versions to run for a while | Purely additive fixes |
Every endpoint carries an EndpointMetadataCollection: a list of objects added by attributes, conventions like WithName, WithTags, RequireAuthorization, and types that implement IEndpointMetadataProvider such as TypedResults. Many features read that list:
IApiDescriptionGroupCollectionProvider) turns it into ApiDescriptions that the OpenAPI generator uses: Produces, ProducesProblem, WithTags, WithSummary.LinkGenerator uses the endpoint name from WithName, which is also the operationId.HttpContext.GetEndpoint().The trade-off: metadata is one source of truth for docs and behaviour, but anything not in metadata (a hand-written IResult, a manual status code) is invisible to the docs.
Adding the Microsoft.Extensions.ApiDescription.Server package makes dotnet build produce the OpenAPI document. It launches your app's entry point with an inert server, asks the registered document provider for each document, and writes {Project}.json to obj (or to OpenApiDocumentsDirectory). Because your start-up code runs during build, guard anything that connects to databases or Key Vault.
I commit the spec: API changes then show up as diffs in pull requests, CI can fail when the regenerated file differs, and clients are generated from a file rather than a running server. For clients I use Kiota (C#, TypeScript, Go, Python...) or NSwag (C#, TypeScript).
The trade-off: a slightly slower build and a guarded Program.cs, in exchange for a contract you can review, diff and generate from.
I make the committed build-time spec the contract and gate pull requests on it:
oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.
How to tell it (STAR)
**S:** A partner of our [payments] API at [company] reported missing bank account details, and their client was generated from our OpenAPI document. **T:** I owned finding out whether it was their client or our contract. **A:** I compared the document with the real JSON, found our base-typed responses weren't serialising derived properties and the document had no `oneOf`, added polymorphism attributes and a string enum converter, coordinated the wire change with partners, and added a snapshot test of the document. **R:** All [3] partners regenerated within [a week], the missing-field tickets stopped, and the snapshot test has since caught [2] unintended contract changes before release.
Last updated 23 Nov 2026.