The Analogy: The Printed Menu
A restaurant prints a menu, and customers order from it. The menu is a promise: this dish exists, it costs this much, it contains these things. If the kitchen quietly renames a dish or changes what it contains, every customer holding last week's menu orders something that no longer exists, and the fault is the kitchen's rather than the customer's.
A public API is a printed menu with the same obligations. Once a client is written against { "total": "12.50" }, renaming that field is not a refactor — it is a broken promise to code you cannot edit. The three practices in this lesson are the restaurant's answers to that problem: check the order form before the kitchen sees it, print a new edition of the menu instead of editing the old one, and generate the menu from the kitchen rather than typing it by hand.
Validation is the order form. It belongs at the edge, it should reject the whole order with every problem listed at once rather than one at a time, and its output should be machine-readable so a client can highlight the offending field instead of showing a paragraph of prose.
Versioning is the edition number, and its purpose is not to let the API change freely but to make change visible. Adding an optional field is safe on any edition; removing one, renaming one or tightening a rule is a new edition. Publishing when the old edition stops being served is as much a part of the contract as the fields themselves.
Syntax or Core Structure
Validation in ASP.NET Core is System.ComponentModel.DataAnnotations, and it works on plain objects — no HTTP required, which makes it easy to see exactly what the framework will do:
using System.ComponentModel.DataAnnotations;
(string Label, ReportRequest Request)[] cases =
{
("valid ", Make(new DateOnly(2026, 1, 1), new DateOnly(2026, 3, 31), "GBP")),
("reversed dates ", Make(new DateOnly(2026, 4, 1), new DateOnly(2026, 1, 1), "GBP")),
("unknown currency ", Make(new DateOnly(2026, 1, 1), new DateOnly(2026, 3, 31), "pounds")),
("missing dates ", Make(null, null, "GBP")),
("eighteen month range ", Make(new DateOnly(2026, 1, 1), new DateOnly(2027, 6, 30), "GBP"))
};
foreach ((string label, ReportRequest request) in cases)
{
List<ValidationResult> results = new List<ValidationResult>();
bool ok = Validator.TryValidateObject(
request, new ValidationContext(request), results, validateAllProperties: true);
Console.WriteLine(label + (ok ? "valid" : "invalid"));
// Reflection order is not guaranteed, so the failures are sorted before printing.
foreach (ValidationResult result in results
.OrderBy(r => string.Join(",", r.MemberNames), StringComparer.Ordinal)
.ThenBy(r => r.ErrorMessage, StringComparer.Ordinal))
{
Console.WriteLine(" " + string.Join(",", result.MemberNames) + ": " + result.ErrorMessage);
}
}
static ReportRequest Make(DateOnly? from, DateOnly? to, string currency) =>
new ReportRequest { From = from, To = to, Currency = currency };
sealed class ReportRequest : IValidatableObject
{
[Required]
public DateOnly? From { get; set; }
[Required]
public DateOnly? To { get; set; }
[Required, CurrencyCode]
public string? Currency { get; set; }
// Cross-field rules cannot live on a single property, so they live here.
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (From is DateOnly from && To is DateOnly to)
{
if (to < from)
{
yield return new ValidationResult("to must not be before from", new[] { nameof(To) });
}
else if (to.DayNumber - from.DayNumber > 365)
{
yield return new ValidationResult(
"range must be 366 days or fewer", new[] { nameof(From), nameof(To) });
}
}
}
}
sealed class CurrencyCodeAttribute : ValidationAttribute
{
private static readonly string[] Allowed = { "GBP", "EUR", "USD" };
protected override ValidationResult? IsValid(object? value, ValidationContext context)
{
if (value is null)
{
return ValidationResult.Success; // [Required] owns the null case
}
string code = value as string ?? string.Empty;
return Array.IndexOf(Allowed, code) >= 0
? ValidationResult.Success
: new ValidationResult(
"currency must be one of GBP, EUR, USD", new[] { context.MemberName! });
}
}
Output:
valid valid
reversed dates invalid
To: to must not be before from
unknown currency invalid
Currency: currency must be one of GBP, EUR, USD
missing dates invalid
From: The From field is required.
To: The To field is required.
eighteen month range invalid
From,To: range must be 366 days or fewer
Four details in that transcript are worth pinning down. First, MemberNames is a collection, not a single string — a cross-field failure can name every field involved, which is how the eighteen-month case blames From and To together. Second, a custom ValidationAttribute returns ValidationResult.Success for null and lets [Required] speak instead; if it rejected null too, an empty request would report two failures for one mistake.
Third, and easy to be caught by: the "missing dates" case does not report a date-range failure. Validator.TryValidateObject runs property attributes first and returns early if any of them failed, so IValidatableObject.Validate never executes. That is the behaviour you want — cross-field rules can assume the individual fields are present — but it means Validate is not a place to put checks you need to run unconditionally.
Fourth, "The From field is required." is the framework's default message, built from the display name. Set [Required(ErrorMessage = "from is required")] or [Display(Name = "start date")] when the property name is not what you want a client to see.
Technical Depth: Three Contracts, One Endpoint
Where validation actually runs
The annotations are the same everywhere; what differs is who invokes them.
| Host | Runs DataAnnotations? | How |
|---|---|---|
Controller with [ApiController] | Yes, automatically | Model binding fills ModelState; a filter returns 400 before your action runs |
Controller without [ApiController] | Populates ModelState, but does not stop | You must check ModelState.IsValid yourself |
| Minimal API | No | Nothing calls Validator for you unless you add a filter or call it by hand |
Manual (Validator.TryValidateObject) | Yes | Anywhere — background workers, domain services, tests |
The minimal-API row is the one that surprises people. A record parameter with [Required] on every property will happily bind a request full of nulls and hand it to your handler. The fix is the endpoint filter pattern from the minimal-APIs lesson, applied once to a group rather than repeated per endpoint.
Layer the checks rather than choosing one place for all of them:
- Shape — is this parseable and are the required fields present? Annotations, at the edge, returning 400.
- Semantics — is this range sane, is this currency one we settle in? Annotations or
IValidatableObject, still at the edge, still 400. - State — does this order exist, is this SKU still stocked? Needs a database, belongs in the service, and usually answers 404 or 409 rather than 400.
Never let a state check masquerade as validation. "Unknown SKU" is not a malformed request; it is a request about something that does not exist.
The shape of a validation response
RFC 9457 (formerly RFC 7807) defines application/problem+json, and ASP.NET Core implements it as ProblemDetails with a validation-specific subclass:
| Field | Meaning | Notes |
|---|---|---|
type | URI identifying the kind of error | Framework-supplied by default; supply your own for domain errors |
title | Short, stable human summary | Should not change per occurrence |
status | Duplicate of the HTTP status | Convenient for clients that only read the body |
detail | What went wrong this time | Safe to vary; never put secrets or stack traces here |
instance | Which request | Often the path |
errors | field -> string[] map | ValidationProblemDetails only |
| extensions | Any extra members you add | traceId is added automatically when problem details are enabled |
builder.Services.AddProblemDetails(); // makes unhandled and 4xx/5xx responses problem+json
// Controllers: hand ModelState straight over.
return ValidationProblem(ModelState);
// Minimal APIs: build the dictionary yourself.
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
["quantity"] = new[] { "quantity must be 1-100" }
});
Return every failure in one response. A client that must submit five times to discover five problems will hard-code a guess at your rules instead.
Choosing a versioning scheme
| Scheme | Looks like | For | Against |
|---|---|---|---|
| URL segment | /api/v2/orders | Visible in logs, curl-able, trivially cacheable, easy to route | The version leaks into every client URL |
| Query string | /api/orders?api-version=2.0 | Same route table, easy to default | Easy to forget; muddies cache keys |
| Custom header | X-Api-Version: 2.0 | Keeps URLs clean and resource-shaped | Invisible in a browser and in most logs |
| Media type | Accept: application/json;v=2 | The most correct answer per HTTP | Almost no client library makes it pleasant |
Pick one and apply it everywhere. Two schemes in one API means clients that pin a version in the URL and a different one in a header, and you will not find out until something breaks.
The Asp.Versioning.Http and Asp.Versioning.Mvc packages implement all four, plus the reporting headers, so you rarely need to hand-roll:
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = false; // be explicit; see below
options.ReportApiVersions = true; // adds api-supported-versions
options.ApiVersionReader = new UrlSegmentApiVersionReader();
});
AssumeDefaultVersionWhenUnspecified = true is tempting and usually wrong for a public API: every unversioned client is silently pinned to v1 and will break on the day you retire it. Rejecting the request tells the client, at integration time, that a decision is required.
What actually breaks a client
| Change | Breaking? | Why |
|---|---|---|
| Add an optional response field | No | Unknown members are ignored by well-behaved deserialisers |
| Add an optional request field | No | Omitting it keeps the old behaviour |
| Add a required request field | Yes | Every existing call becomes a 400 |
| Rename or remove a field | Yes | Nothing to map to |
Change a type ("12.50" to 1250) | Yes | Silent misreads are worse than errors |
| Tighten a rule (max 1000 to max 100) | Yes | Previously valid calls now fail |
| Loosen a rule | No | Nothing that worked stops working |
| Add a new enum value in a response | Usually | Clients with an exhaustive switch throw |
| Change an error status code | Yes | Retry and alerting logic is keyed on status |
| Reorder JSON properties | No | JSON objects are unordered |
The "add an enum value" row is the sneaky one. Send "status": "partially_shipped" to a client whose switch covers three cases and you have shipped a breaking change without touching a field name.
Retiring an edition
Deprecation is an announcement, not a deletion. HTTP has headers for it:
Deprecation: true— this endpoint or version is deprecated as of now.Sunset: Wed, 01 Jul 2026 00:00:00 GMT— the date after which it stops answering (RFC 8594, an HTTP-date).Link: <https://docs.example.com/v2>; rel="deprecation"— where to read about the replacement.api-supported-versions/api-deprecated-versions— what else this service speaks.
Serve them for the entire notice period, watch your logs for callers still using the old edition, and contact them before the sunset date rather than after.
OpenAPI: the menu, printed from the kitchen
A hand-written API document is wrong within a week. OpenAPI documents are generated from the metadata your endpoints already carry — routes, parameter types, response types, attributes — which is why every metadata call you make pays off twice: once as a compiler-checked description, once as documentation.
builder.Services.AddOpenApi(); // Microsoft.AspNetCore.OpenApi
WebApplication app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); // serves /openapi/v1.json
}
app.MapGet("/api/v2/orders/{id:int}", (int id) => TypedResults.Ok(new OrderV2(id, 1250, "GBP")))
.WithName("GetOrderV2")
.WithSummary("Fetch a single order")
.WithTags("Orders")
.Produces<OrderV2>(StatusCodes.Status200OK)
.ProducesProblem(StatusCodes.Status404NotFound);
| Tool | What it adds | Applies to |
|---|---|---|
.WithName(...) | operationId, and enables LinkGenerator | Minimal APIs |
.WithSummary / .WithDescription | Prose in the document | Minimal APIs |
.WithTags(...) | Groups operations in the UI | Minimal APIs |
.Produces<T>(status) | A documented response body and status | Minimal APIs |
.ProducesValidationProblem() | The 400 errors shape | Minimal APIs |
[ProducesResponseType(typeof(T), 200)] | Same as Produces, attribute form | Controllers |
[Tags("Orders")], XML doc comments | Grouping and prose | Controllers |
[FromBody], [FromQuery], [Required] | Parameter location and schema constraints | Both |
Two habits matter more than the rest. Give every response status a documented type, including the failure ones — a generated client that knows a 400 carries errors can surface field-level messages, while one that sees an undocumented 400 can only show "Bad Request". And emit one document per API version (AddOpenApi("v1"), AddOpenApi("v2")) so a client generating code for v1 never sees v2's fields.
Swashbuckle (Swashbuckle.AspNetCore) is the long-standing alternative and still the usual way to get a browsable Swagger UI; from .NET 9 the document generation itself is built in, and UIs such as Scalar or Swagger UI can be pointed at /openapi/v1.json. Do not expose the document publicly without thinking about it: it is a complete map of your surface area, including the endpoints you forgot were there.
Real World Example: Two Editions, Served Side by Side
The point of versioning is that both editions are live. This host serves v1 and v2 of one resource, announces v1's retirement in headers, and refuses an unversioned request instead of guessing:
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
const string BaseUrl = "http://localhost:5217";
const string SunsetDate = "Wed, 01 Jul 2026 00:00:00 GMT";
WebApplicationBuilder builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls(BaseUrl);
builder.Logging.ClearProviders();
WebApplication app = builder.Build();
// --- edition 1: deprecated, but still answering until the sunset date ---
RouteGroupBuilder v1 = app.MapGroup("/api/v1")
.AddEndpointFilter(async (context, next) =>
{
object? result = await next(context);
// The result has not executed yet, so the headers are still writable.
IHeaderDictionary headers = context.HttpContext.Response.Headers;
headers["api-supported-versions"] = "1.0, 2.0";
headers["Deprecation"] = "true";
headers["Sunset"] = SunsetDate;
return result;
});
v1.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new OrderV1(id, "12.50")))
.WithName("GetOrderV1")
.WithTags("Orders")
.Produces<OrderV1>();
// --- edition 2: current. Money is minor units, currency is explicit, one field added ---
RouteGroupBuilder v2 = app.MapGroup("/api/v2")
.AddEndpointFilter(async (context, next) =>
{
object? result = await next(context);
context.HttpContext.Response.Headers["api-supported-versions"] = "1.0, 2.0";
return result;
});
v2.MapGet("/orders/{id:int}", (int id) =>
TypedResults.Ok(new OrderV2(id, 1250, "GBP", Placed: new DateOnly(2026, 2, 14))))
.WithName("GetOrderV2")
.WithTags("Orders")
.Produces<OrderV2>();
// --- unversioned: refuse, and name what is on offer ---
ProblemDetails unsupported = new ProblemDetails
{
Title = "Unsupported API version",
Detail = "use /api/v1/orders or /api/v2/orders",
Status = StatusCodes.Status400BadRequest
};
unsupported.Extensions["supportedVersions"] = new[] { "1.0", "2.0" };
app.MapGet("/api/orders/{id:int}", () => TypedResults.Problem(unsupported));
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
string[] paths =
{
"/api/v1/orders/1", // deprecated edition
"/api/v2/orders/1", // current edition
"/api/v3/orders/1", // an edition that does not exist
"/api/orders/1" // no edition named at all
};
foreach (string path in paths)
{
using HttpResponseMessage response = await client.GetAsync(path);
string body = await response.Content.ReadAsStringAsync();
Console.WriteLine((int)response.StatusCode + " GET " + path);
Console.WriteLine(" " + VersionHeaders(response));
Console.WriteLine(" " + Summarise(body));
}
await app.StopAsync();
static string VersionHeaders(HttpResponseMessage response)
{
string[] names = { "api-supported-versions", "Deprecation", "Sunset" };
List<string> parts = new List<string>();
foreach (string name in names)
{
if (response.Headers.TryGetValues(name, out IEnumerable<string>? values))
{
parts.Add(name.ToLowerInvariant() + "=" + string.Join(";", values));
}
}
return parts.Count == 0 ? "(no version headers)" : string.Join(" ", parts);
}
// Problem bodies carry framework-supplied members that vary by release, so only
// the fields this code set are read back.
static string Summarise(string body)
{
if (string.IsNullOrWhiteSpace(body))
{
return "(no body)";
}
using JsonDocument document = JsonDocument.Parse(body);
JsonElement root = document.RootElement;
if (!root.TryGetProperty("title", out JsonElement title))
{
return body;
}
string supported = root.TryGetProperty("supportedVersions", out JsonElement versions)
? " supported=" + versions.GetRawText()
: string.Empty;
return "problem: " + title.GetString()
+ " " + root.GetProperty("status").GetInt32()
+ " - " + root.GetProperty("detail").GetString()
+ supported;
}
record OrderV1(int Id, string Total);
record OrderV2(int Id, int TotalCents, string Currency, DateOnly Placed);
Output:
200 GET /api/v1/orders/1
api-supported-versions=1.0, 2.0 deprecation=true sunset=Wed, 01 Jul 2026 00:00:00 GMT
{"id":1,"total":"12.50"}
200 GET /api/v2/orders/1
api-supported-versions=1.0, 2.0
{"id":1,"totalCents":1250,"currency":"GBP","placed":"2026-02-14"}
404 GET /api/v3/orders/1
(no version headers)
(no body)
400 GET /api/orders/1
(no version headers)
problem: Unsupported API version 400 - use /api/v1/orders or /api/v2/orders supported=["1.0","2.0"]
The two editions differ only in their shape. In a real service both handlers would call the same IOrderService and differ solely in how they project the result — v1 mapping money to "12.50", v2 to 1250 plus a currency. Duplicating the business logic per version is how a codebase ends up with two subtly different definitions of a discount; duplicating only the DTO and the mapping keeps the divergence in one small, deletable place.
The change from "total": "12.50" to "totalCents": 1250 is a textbook breaking change, and it is the reason v2 exists. Note that the field was also renamed: had v2 kept the name total while changing its type and meaning, every client that upgraded would have compiled, deserialised without complaint, and then billed someone 1250 pounds. When you change what a value means, change its name too — a loud failure beats a silent one.
Compare the last two responses. /api/v3/orders/1 produces a bare 404 because no route matched, which tells a client nothing about what is available; /api/orders/1 produces a 400 that names both live editions. That gap is exactly what the versioning packages close, by matching the version as a parameter and reporting supported versions on the failure. Add app.UseStatusCodePages() alongside AddProblemDetails() and even that empty 404 becomes a problem+json body, so a client never has to guess from a status code alone.
The header writes sit after await next(context) on purpose. An endpoint filter runs before the result is executed, so the response has not started and Headers[...] still works — the same code inside middleware placed after app.Run would throw, because once bytes are on the wire the headers are sealed. Attaching the filter to the group rather than to each endpoint means the sunset date lives in exactly one place: when v1 is finally retired, one MapGroup call and its DTO are deleted, and nothing else in the service moves.
Common Mistakes
- Assuming minimal APIs validate for you.
[Required]on a record parameter does nothing unless a filter callsValidator, or you call it yourself. Controllers with[ApiController]do it automatically; minimal APIs do not. - Returning one failure at a time. Validating with early returns forces a client through a submit-fix-submit loop. Collect every failure and return them together in
errors. - Putting state checks in validation. "Unknown SKU" or "order already shipped" are not 400s. They need data, and they belong in the service returning 404 or 409.
- Rejecting
nullinside a customValidationAttribute.[Required]already covers absence, so a null-rejecting attribute reports one mistake twice. ReturnValidationResult.Successfornull. - Expecting
IValidatableObject.Validateto always run.Validatorshort-circuits when property attributes have already failed, so cross-field rules never see a request that is missing a required field. - Leaking internals in
detail. Exception messages, SQL fragments, file paths and connection strings all end up in client logs and bug reports.titlestays stable;detailstays generic. AssumeDefaultVersionWhenUnspecified = trueon a public API. Every unversioned client is silently pinned to v1 and breaks on the day you retire it, with no record of having chosen anything.- Treating "additive" as automatically safe. A new required request field, a tightened maximum, or a new enum value in a response will each break real clients despite adding nothing you would call a removal.
Best Practices
- Validate at the edge, in one reusable place. A group-level endpoint filter or
[ApiController]beats a validation block copied into every handler, because the copy that gets forgotten is the one that ships. - Answer with problem+json everywhere. Register
AddProblemDetails()andUseStatusCodePages()so a client parses one error shape whether the failure came from your code, from routing, or from the framework. - Keep
titlestable and machine-friendly. Clients switch ontypeandstatus; humans readdetail. Changing atitleper occurrence makes error aggregation useless. - Choose one versioning scheme and never mix. URL segments are the pragmatic default: visible in logs, cacheable, and obvious in a bug report.
- Version the contract, not the logic. New DTOs and a mapping layer per edition; one implementation underneath. Two copies of the rules will diverge.
- Announce retirement in headers, not just in a blog post.
Deprecation,Sunsetand aLinkto the migration guide reach the client's own logs, which is the only place their on-call engineer will look. - Document every status you can return, with its body type.
.Produces<T>(200)plus.ProducesValidationProblem()lets a generated client show field-level errors instead of the words "Bad Request". - Generate one OpenAPI document per version and diff it in CI. A pull request that changes the document changes the contract; making the diff visible turns accidental breaks into a review comment.
Practice Exercises
- Cross-field validation. Write a
TransferRequestwithFromAccount,ToAccountandAmountMinorUnits, using[Required]and[Range]for shape andIValidatableObjectto reject a transfer to the same account. Drive it withValidator.TryValidateObjectover five cases, printing failures sorted by member name, and confirm for yourself that the same-account rule does not run whenToAccountis missing. - A reusable validation filter. Take the
ReportRequestmodel and expose it from a minimal-API POST endpoint. Add a group-level endpoint filter that runsValidator.TryValidateObject, converts theValidationResultlist into aDictionary<string, string[]>keyed by member name, and returnsTypedResults.ValidationProblem. Verify that a request with two bad fields comes back as one 400 listing both. - Deprecation with a decision date. Extend the two-edition host so v1 returns 410 Gone with a problem body once the sunset date has passed, driving the comparison from an injected clock rather than
DateTime.UtcNow. Prove both branches by running the host twice with a clock set either side of the date, and keep the output free of real timestamps. - Contract diffing. Add
AddOpenApi("v1")andAddOpenApi("v2"), annotate both endpoints with.Produces,.WithSummaryand.WithTags, and save each generated document to a file. Now make a deliberately breaking change — rename a field in v2 — regenerate, and diff the documents. Write down which lines a reviewer would need to see to catch the break.