Start learning free

LESSON 27 OF 173 · BACKEND: YOUR FIRST API

JSON for Unknown Paths

Practice

Your routes send errors as JSON. But when a path has no route at all, like /contact, none of your code runs: ASP.NET answers 404 by itself, with an empty body. A program that expects {"error": ...} finds nothing to read.

ASP.NET lets you fill those empty answers with app.UseStatusCodePages. You give it an async function, and it calls that function whenever an answer has an error status and no body yet. No route ran, so nothing sends an IResult for you: you call its ExecuteAsync(context.HttpContext) and await it. Here is one that fills 405 answers (not part of this lesson):

app.UseStatusCodePages(async context => {
    if (context.HttpContext.Response.StatusCode == 405) {
        await Results.Json(new { error = "Method not allowed" }, statusCode: 405)
            .ExecuteAsync(context.HttpContext);
    }
});

Status code pages only fill answers that have no body. A route that returns its own 404, like the GET route for one product, keeps its own message, and the 405 for a wrong method stays empty, because your function only acts on 404. The requests and answers your code must give, in this order:

GET /contact  →  404  {"error": "Not found"}
GET /products/abc  →  404  {"error": "Not found"}
POST /orders  {"product_id": 1, "quantity": 2}  →  404  {"error": "Not found"}
GET /products/9  →  404  {"error": "Product not found"}
DELETE /products  →  405  (empty body, as before)
GET /about  →  200  {"name": "Corner Shop", "currency": "USD"}

Your task: under ErrorResponse, call app.UseStatusCodePages with an async function that, for a 404, sends {"error": "Not found"} with status 404 through your ErrorResponse helper.


Assignment
Follow the Coding Tutorial to make every 404 ASP.NET sends by itself answer in JSON.


Hint
Compare context.HttpContext.Response.StatusCode with 404, a number without quotes. Calling ErrorResponse only builds the answer: without ExecuteAsync, nothing sends it.


STEP 1 OF 3
    Ctrl + Enter to check