Start learning free

LESSON 17 OF 173 · BACKEND: YOUR FIRST API

When It Isn't There in C#

Practice

When no product has the id that was asked for, the loop in the /products/{id:int} route ends, and nothing comes after it. C# checks this before the app even starts: a lambda that returns a result on one path must return one on every path. So the compiler stops with error CS1643, "Not all code paths return a value", and no request gets an answer. Nothing is wrong with the request: the product just isn't there, and your code has to say so.

The status code tells the client how its request went: 200 means OK, 404 means Not Found, 500 means the server failed. Results.Json(…) sends 200. To send another status, add statusCode: and the number after the body, separated by a comma. For example, a members-only page could answer 403, which means Forbidden:

app.MapGet("/vip", () => {
    return Results.Json(new { error = "Members only" }, statusCode: 403);
});

An API answers its errors in JSON too, like {"error": "Product not found"}, so the client's program can read what went wrong. In C#, new { … } makes such an object without writing a class. The error belongs after the loop: those lines run only when no product matched.

Your app must answer:

GET /products/99    →  404  {"error": "Product not found"}
GET /products/2     →  200  {"id": 2, "name": "Notebook", "price": 7, "category": "office"}
GET /products/0     →  404  {"error": "Product not found"}
GET /products/5     →  404  {"error": "Product not found"}
GET /products/lamp  →  404  (empty body)

Your task: after the loop in the /products/{id:int} route, put a new object in error with error = "Product not found" inside its braces, and return it with Results.Json and statusCode: 404.


Assignment
Follow the Coding Tutorial to answer 404 with a JSON error when no product has the requested id.


Hint
The two new lines go after the loop's closing }, indented like the foreach line, not inside it. statusCode: 404 comes after the object, separated by a comma.


STEP 1 OF 2
    Ctrl + Enter to check

    Shop Not Found in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free