liveBook · Manning

Result resource

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

ActionResult<T> is an ASP.NET Core MVC result type that allows an action method to return either a typed value or an arbitrary HTTP action result.

Use ActionResult<T> when a web API action may return either a value of type T or another HTTP result. An action that only returns data can return that data directly; ActionResult<T> becomes useful when the same action must also handle an error. section 20.1 section 20.7

Return a fruit or a 404

A GET action declared as ActionResult<string> checks whether an ID is within the fruit list. For a valid ID, it returns the string, which is serialized into a 200 OK response. Otherwise, it returns NotFound(). With [ApiController], the 404 error response uses ProblemDetails format. section 20.1

Listing 20.3 A web API action returning IActionResult to handle error conditions
[HttpGet("fruit/{id}")]                     #1
public ActionResult<string> View(int id)    #2
{
    if (id >= 0 && id < _fruit.Count)       #3
    {
        return _fruit[id];                  #4
    }
    return NotFound();                      #5
}

The action signature and its two return paths show why ActionResult<string> is needed. section 20.1

When unit-testing an API controller, check the action’s own decisions rather than assuming the test runs routing, model binding, or filters. A controller test can supply input directly; a validation-error test can add an error to ModelState before calling the action. section 36.2

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

How deep it goes
Works through a conditional controller action and response behavior, without examining the result type’s internals.
Examples
Uses a fruit lookup returning a string or NotFound(), plus a currency-conversion action tested with supplied input.
What it assumes
Starts with creating a web API project and a simple controller before adding conditional results.
What you can do after
Apply it via ASP.NET Core MVC to write an API action with typed success and error return paths.
How it connects
Connects API controllers, HTTP status codes, JSON serialization, [ApiController], ProblemDetails, and controller unit testing.

Also explained in

Compare how 4 books explain result resource →

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.