Menu
CoddyTech

Rejecting Bad Input

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

A body can bind and still make no sense: an empty email, a negative price. Answer 400 Bad Request and say what is wrong in a shape clients can read. Results.ValidationProblem takes a dictionary from field name to messages:

if (string.IsNullOrWhiteSpace(input.Email))
{
    return Results.ValidationProblem(new Dictionary<string, string[]>
    {
        ["email"] = ["Email is required."],
    });
}

It answers 400 with the content type application/problem+json and this body:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": { "email": ["Email is required."] } }

Check before you change anything, so a refused request leaves the data as it was. A body that is not valid JSON never reaches your lambda: ASP.NET Core answers 400 for it.

challenge icon

Challenge

Easy

Right now POST /api/tasks with { "title": "" } adds a task with no title. Refuse it.

  1. At the start of the POST /api/tasks lambda, before nextId++, check the title with string.IsNullOrWhiteSpace(input.Title). It catches a missing title (null), an empty one and one made of spaces.
  2. When it fails, answer Results.ValidationProblem with the field title and the message Title is required., so the body holds:
    "errors": { "title": ["Title is required."] }
  3. Add the same check at the start of the PUT /api/tasks/{id:int} lambda.

Try it: press Run and POST { "title": "" } to /api/tasks: 400 and the errors above. Send GET /api/tasks: still three tasks. PUT { "title": " ", "done": true } to /api/tasks/1: 400, and task 1 keeps its title. POST { "title": "Order new chairs" }: 201 with id 4.

Try it yourself

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 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 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(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