liveBook · Manning

StatusCodeResult

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

StatusCodeResult is an ASP.NET Core action result that returns a specified HTTP status code, optionally with response content.

StatusCodeResult is an ASP.NET Core action result for returning an explicitly selected HTTP status code. For example, setting the status code to 404 produces a raw not-found response. section 15.4.2

The result sends the status code through the middleware pipeline without generating HTML. That behavior suits APIs, where responses are machine-friendly, but often gives Razor Pages users only a generic browser error page. section 15.4.2 section 20.1

Returning a not-found status

An action can return an IActionResult such as StatusCodeResult and explicitly select 404 when a requested product or other resource does not exist. In a web API, returning NotFound() provides the corresponding error response; the [ApiController] attribute can format that response as ProblemDetails. section 15.4.2 section 20.1

Figure 15.4 If you return a raw 404 status code without any HTML, the browser will render a generic default page instead. The message is of limited utility to users and may leave many of them confused or thinking that your web application is broken.
CH15_F04_Lock3

A raw 404 response can cause the browser to display a generic default page instead of a useful application-specific explanation. section 15.4.2

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

How deep it goes
Defines raw status-code behavior and contrasts API use with Razor Pages, but defers custom HTML error handling.
Examples
Uses a missing e-commerce product and a web API action handling an invalid fruit identifier.
What it assumes
Assumes basic action methods and HTTP responses while introducing the distinction between machine-friendly API output and HTML pages.
What you can do after
Apply it by returning an explicit status code for API error conditions and recognizing when raw responses need friendlier handling.
How it connects
Connects HTTP status codes, IActionResult, NotFoundResult, Razor Pages, web API controllers, middleware, and ProblemDetails.

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.