liveBook · Manning

HTTP 404 error

As explained in ASP.NET Core in Action, 3e

The HTTP 404 status code indicates that the server cannot find the resource or endpoint identified by the request path.

HTTP 404 Not Found means that the requested resource could not be found. It can occur automatically when no endpoint matches a request URL, such as when a user enters an invalid address. An application can also return 404 when an endpoint exists but the requested entity does not. section 15.5 section 5.3.1

Return 404 for a missing fruit

A minimal API can look up the ID in GET /fruit/{id}. If the fruit exists, TypedResults.Ok(fruit) returns it with a 200 response; otherwise, Results.NotFound() returns 404. Whether to use 404 for a missing entity as well as an unmatched endpoint is a matter of debate. section 5.3.1

Listing 5.3 Using Results and TypedResults in a minimal API
using System.Collections.Concurrent;
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
var _fruit = new ConcurrentDictionary<string, Fruit>();        #1
 
app.MapGet("/fruit", () => _fruit);
 
app.MapGet("/fruit/{id}", (string id) =>
    _fruit.TryGetValue(id, out var fruit)                      #2
        ? TypedResults.Ok(fruit)                               #3
        : Results.NotFound());                                 #4
 
 
app.MapPost("/fruit/{id}", (string id, Fruit fruit) =>
    _fruit.TryAdd(id, fruit)                                   #5
        ? TypedResults.Created($"/fruit/{id}", fruit)          #6
        : Results.BadRequest(new                               #7
            { id = "A fruit with this id already exists" }));  #7
 
app.MapPut("/fruit/{id}", (string id, Fruit fruit) =>
{
 
    _fruit[id] = fruit;
    return Results.NoContent();                                #8
});
 
app.MapDelete("/fruit/{id}", (string id) =>
{
    _fruit.TryRemove(id, out _);                               #9
    return Results.NoContent();                                #9
});
 
app.Run();
record Fruit(string Name, int stock);
#1 Uses a concurrent dictionary to make the API thread-safe
#2 Tries to get the fruit from the dictionary. If the ID exists in the dictionary, this returns true . . .
#3 . . . and we return a 200 OK response, serializing the fruit in the body as JSON.
#4 If the ID doesn’t exist, returns a 404 Not Found response
#5 Tries to add the fruit to the dictionary. If the ID hasn’t been added yet. this returns true . . .
#6 . . . and we return a 201 response with a JSON body and set the Location header to the given path.
#7 If the ID already exists, returns a 400 Bad Request response with an error message
#8 After adding or replacing the fruit, returns a 204 No Content response
#9 After deleting the fruit, always returns a 204 No Content response

See the fruit lookup alongside other minimal API results. section 5.3.1

For an API, a status code without additional content can be sufficient. In a user-facing Razor Pages application, a generic error page may be confusing, so a page consistent with the rest of the application can be more helpful. section 15.5

StatusCodePagesMiddleware can handle error status codes. Add it early in the middleware pipeline so it can handle errors from later components. The basic app.UseStatusCodePages() intercepts 4xx and 5xx responses that have no body; its default page is mainly useful for confirming that interception works. section 15.5

For a more consistent error page, app.UseStatusCodePagesWithReExecute("/{0}") can reexecute the pipeline to generate a response. For example, a 404 can be handled using /404. The redirect alternative instead sends a 302 and makes the browser request /404 separately. section 15.5

Test an API’s responses in Swagger UI by selecting an endpoint, choosing Try it out, entering the required parameters, and choosing Execute. If a request reveals a possible 404 that the endpoint documentation omits, add metadata to document that response. section 11.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains 404 generation and application handling, including middleware placement and error-page alternatives.
Examples
Uses a fruit lookup, an invalid URL, and a missing product to illustrate 404 responses.
What you can do after
Apply it via ASP.NET Core results and status-code middleware, and test responses with Swagger UI.
How it connects
Connects 404 responses to endpoint routing, HTTP status codes, middleware, and OpenAPI documentation.

Also explained in

Compare how 3 books explain HTTP 404 error →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.