Validation and HTTP status
Validation and HTTP status
Validation checks whether a successfully received request meets application rules. HTTP status codes distinguish bad input, missing resources, conflicts and successful operations. Problem Details gives clients a structured error representation instead of exposing internal exceptions.
Binding errors concern whether data can be read into a type; semantic validation concerns whether the values are acceptable. A request can contain valid JSON with a negative quantity. Return a 400 validation problem with field errors when the request violates the declared rules, 404 for a missing resource, and 409 for a conflicting current state. A 201 response should identify a created resource when applicable; 204 carries no response body. Idempotency means repeating a request has the same intended effect, not necessarily the same response status. Conditional requests using If-Match and ETags can avoid lost updates; a failed precondition is typically 412. Production changes need atomic concurrency control. .NET 10 also introduces opt-in Minimal API validation through AddValidation and data annotations; these fixtures use explicit checks to make the rules visible without adding a package dependency. For generated Minimal API validation, register AddValidation in the assembly that defines the endpoints; verify the generated behavior under the selected .NET 10 patch. Data-annotation validation is not authorization, does not reject unknown JSON members by itself, and cannot replace transactional domain invariants. Never leak stack traces, secrets, or database exceptions.
Baseline: .NET 10 / C# 14. Each code block is an independent static example with a companion Web SDK project. Read the endpoint registration and client checks first; the surrounding host harness is repeated for standalone use. Expected observations are reasoned, not executed. Run only in a clean, isolated local environment with an approved SDK; no launch profile, external network or real data. The OpenAPI package example additionally requires approved restore.
Return a field-level validation problem
A quantity from 1 to 5 is acceptable; parse success is not validation success.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapPost("/estimate", (QuantityDto input) =>{ if (input.Quantity is < 1 or > 5) return Results.ValidationProblem(new Dictionary<string, string[]> { ["quantity"] = new[] { "Use 1 through 5." } }); return Results.Ok(input.Quantity * 2);});using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var bad = await client.PostAsJsonAsync("/estimate", new { quantity = 0 }, deadline.Token); using var doc = JsonDocument.Parse(await bad.Content.ReadAsStringAsync(deadline.Token)); Console.WriteLine((int)bad.StatusCode); Console.WriteLine(doc.RootElement.GetProperty("errors").GetProperty("quantity")[0].GetString()); using var good = await client.PostAsJsonAsync("/estimate", new { quantity = 5 }, deadline.Token); Console.WriteLine($"{(int)good.StatusCode}:{await good.Content.ReadAsStringAsync(deadline.Token)}");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record QuantityDto(int Quantity);The explicit problem identifies the invalid field and the valid boundary is accepted.
Expected observation (reasoned, not executed):
400Use 1 through 5.200:10Distinguish created from conflict
A concurrent dictionary makes the insert decision atomic for this single-process toy catalog.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();var items = new System.Collections.Concurrent.ConcurrentDictionary<int, string>();app.MapPost("/books", (BookInput input) =>{ if (input.Id < 1 || string.IsNullOrWhiteSpace(input.Title)) return Results.BadRequest(); if (!items.TryAdd(input.Id, input.Title)) return Results.Conflict(); return Results.Created($"/books/{input.Id}", input);});app.MapGet("/books/{id:int}", (int id) => items.TryGetValue(id, out var title) ? Results.Ok(new BookInput(id, title)) : Results.NotFound());using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var first = await client.PostAsJsonAsync("/books", new { id = 4, title = "River Guide" }, deadline.Token); Console.WriteLine($"{(int)first.StatusCode}:{first.Headers.Location}"); using var second = await client.PostAsJsonAsync("/books", new { id = 4, title = "River Guide" }, deadline.Token); Console.WriteLine((int)second.StatusCode); using var read = await client.GetAsync("/books/4", deadline.Token); Console.WriteLine((int)read.StatusCode);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record BookInput(int Id, string Title);The first insert creates the resource; duplicate ID conflicts; the location can be read. In-memory state disappears at shutdown.
Expected observation (reasoned, not executed):
201:/books/4409200Make error bodies safe
ProblemDetails describes an expected missing resource without exposing private state.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/orders/{id:int}", (int id) => id == 1 ? Results.Ok(new { id = 1, state = "ready" }) : Results.Problem(statusCode: 404, title: "Order not found"));using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var response = await client.GetAsync("/orders/8", deadline.Token); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(deadline.Token)); Console.WriteLine(response.Content.Headers.ContentType!.MediaType); Console.WriteLine(doc.RootElement.GetProperty("status").GetInt32()); Console.WriteLine(doc.RootElement.GetProperty("title").GetString());}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}A predictable error representation communicates the issue without exposing internal exceptions.
Expected observation (reasoned, not executed):
application/problem+json404Order not foundCommon mistakes and design boundaries
Never return 200 for every error or use 500 for expected invalid input. Do not treat JSON parsing or client-side validation as sufficient. A check-then-insert sequence can race; the toy dictionary does not provide durable or multi-instance consistency. Use server-side authorization even for apparently valid IDs.
Apply your understanding
Design POST /reservations for quantity 1–3 and a unique reservation ID. Specify responses for quantity 0, a successful insert, and a duplicate ID.
Complete the linked manual practice and knowledge check. The examples are not automated ByteMind assessments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validation and HTTP status — knowledge check
Apply the lesson concepts to the following scenarios.
Valid JSON contains quantity 0, outside 1–5. What is appropriate?
What status suits a new resource created successfully?
A unique ID already exists. What status represents the conflict?
Why use TryAdd instead of ContainsKey then Add?
What should a public error response avoid?