liveBook · Manning

IActionResult

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

IActionResult is an ASP.NET Core interface representing instructions for producing an HTTP response from request-handling code.

IActionResult represents instructions for producing an HTTP response. A Razor Page handler chooses and returns a result; the Razor Pages infrastructure executes it to generate the response. This separates the decision about what to send from the work of generating it, so each can be tested separately. section 15.4

Common result types include:

  • PageResult generates HTML for the associated Razor Page with a 200 response; ViewResult generates HTML from a Razor view in an MVC controller. section 15.4
  • RedirectToPageResult sends a 302 redirect to another page; RedirectResult sends a 302 redirect to a specified URL. section 15.4
  • FileResult and its derived types return files; ContentResult returns a string; StatusCodeResult sends a raw HTTP status code. section 15.4

A Razor Page handler can also return void to render its associated template. Use an IActionResult when the handler needs different instructions, such as a redirect or an error response. In web APIs, controller actions can return raw .NET objects or results such as StatusCodeResult. section 13.1.4 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
}

This action returns a fruit value for a valid ID and NotFound() for an invalid ID. Its ActionResult<string> return type accommodates both outcomes. section 20.1

Choose IActionResult rather than IResult for Razor Pages and MVC controllers. IResult is used in minimal APIs; although IResult types execute in Razor Pages and MVC controllers in .NET 7, they do not have all the same features as IActionResult. section 15.4

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

How deep it goes
Explains result execution, testing separation, and common result types, with a worked web API action.
Examples
Uses a fruit API action that returns a value for a valid ID or NotFound() otherwise.
What you can do after
Apply it via ASP.NET Core to select HTML, redirect, file, content, or status responses.
How it connects
Connects response results to MVC, Razor Pages, HTTP redirects, and filters.

Also explained in

Compare how 2 books explain IActionResult →

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.