Menu
CoddyTech

Problem Details

Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 8 of 20.

An empty 404 body leaves the client guessing what went wrong. Problem details (RFC 9457) is the standard JSON shape for an error, sent with the content type application/problem+json. Your 400s already use it. In an orders API, three lines give every error the same shape:

builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

Now GET /api/orders/7 for a missing order answers 404 with:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found", "status": 404,
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00" }

AddProblemDetails registers the service that writes the shape. UseStatusCodePages gives a problem body to every error answer that has none, from your Results.NotFound() or from a path with no route. UseExceptionHandler turns an unhandled exception into a 500 problem. traceId is new on every request; it ties the answer to the server's logs.

challenge icon

Challenge

Easy

Give the task tracker's errors one shape, so a client reads every failure the same way.

  1. In Program.cs, on the line before builder.Build(), add builder.Services.AddProblemDetails();
  2. Right after builder.Build(), add app.UseExceptionHandler(); and then app.UseStatusCodePages();, before any endpoint.

Change nothing else: your endpoints keep answering Results.NotFound(), and the middleware fills in the body. GET /api/tasks/99 then answers 404 with the content type application/problem+json and:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5", "title": "Not Found", "status": 404, "traceId": "..." }

Try it: press Run and send GET /api/tasks/99: the 404 above. Send GET /api/projects, a path with no route: the same shape. POST { "title": "" } to /api/tasks: your 400 keeps its errors, and gains a traceId.

Try it yourself

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

app.MapGet("/api/tasks", () => tasks);

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in REST APIs