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



