9.3 — Action Results: IActionResult and ActionResult<T>¶
← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.2 Controllers · Next: 9.4 Razor and layouts
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
An action does not write the response. It returns an object describing what the response should be, and the framework executes that afterwards.
IActionResult— any result. Use when an action can return different status codes.ActionResult<T>— the same, but also documents the success type for OpenAPI and lets you returnTdirectly.- Returning
Talone works, but you lose the ability to return a 404 or a 400.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
IActionResult |
an interface | The contract for anything an action can return. One method: ExecuteResultAsync. |
ActionResult<T> |
a class | Wraps either an IActionResult or a T. Documents the success type. |
ObjectResult |
a class | Serialises an object with a status code. What Ok(x) produces. |
StatusCodeResult |
a class | A bare status code, no body. What NotFound() produces. |
ViewResult |
a class | Renders a Razor view. What View() produces. |
CreatedAtRouteResult |
a class | 201 plus a Location header. See 8.6. |
RedirectToActionResult |
a class | A 302 to another action. |
ProblemDetails |
a class | The RFC 7807 error shape. See 10.8. |
TypedResults |
a static class (.NET 7+) | Strongly-typed results for minimal APIs. |
| Result execution | a framework step | Running the returned result to actually produce the response. |
The concept¶
The action returns a description, not a response¶
This is the idea that makes actions testable:
[HttpGet("{id:guid}")]
public async Task<IActionResult> Get(Guid id, CancellationToken ct)
{
var order = await _orders.GetAsync(id, ct);
return order is null ? NotFound() : Ok(order);
}
NotFound() does not write a 404 to the response. It returns a NotFoundResult object. The
framework runs it afterwards, during result execution
(9.1).
That separation means a unit test can inspect what the action decided, with no HTTP involved:
var result = await controller.Get(missingId, CancellationToken.None);
Assert.IsType<NotFoundResult>(result);
A picture: writing a prescription rather than dispensing the medicine. The doctor decides what should happen and writes it down; the pharmacy carries it out. You can check the prescription without opening a pharmacy.
The three return styles¶
// 1. IActionResult — any result, no type documented
public async Task<IActionResult> Get(Guid id) { }
// 2. ActionResult<T> — any result, success type documented
public async Task<ActionResult<OrderDto>> Get(Guid id) { }
// 3. T — only ever success
public async Task<OrderDto> Get(Guid id) { }
Prefer ActionResult<T> for APIs. It gives you both: the flexibility to return NotFound()
and a documented success type that OpenAPI and clients can see
(10.9).
⚠️ Returning T alone is limiting. You cannot return a 404 — throwing is the only option, and
exceptions for expected outcomes are slow and noisy
(1.20).
How it works¶
The simple version — the helpers you will use¶
Success:
Ok() // 200, no body
Ok(dto) // 200 with a serialised body
Created(uri, dto) // 201 with a Location header
CreatedAtRoute("Orders_Get", new { id }, dto) // 201, URL generated from a route name
CreatedAtAction(nameof(Get), new { id }, dto) // 201, URL from a controller/action
NoContent() // 204 — success, nothing to return
Client errors:
BadRequest() // 400
BadRequest("Something was wrong") // 400 with a message
ValidationProblem(ModelState) // 400 as ValidationProblemDetails
Unauthorized() // 401 — we do not know who you are
Forbid() // 403 — we know, and you still cannot
NotFound() // 404
Conflict() // 409
UnprocessableEntity() // 422
Other:
StatusCode(418) // any status code
Problem(detail, statusCode: 500) // ProblemDetails body
File(bytes, "application/pdf", "report.pdf")
PhysicalFile(path, contentType)
Redirect("/other") // 302
RedirectToAction(nameof(Index)) // 302 to an action
RedirectPermanent("/moved") // 301
Views — Controller only (9.2):
View() // the view matching the action name
View(model) // with a model
View("OtherView", model) // a named view
PartialView("_Row", model) // a partial, for AJAX
⚠️ 401 versus 403¶
The distinction that gets asked about:
| Meaning | |
|---|---|
| 401 Unauthorized | "I do not know who you are." Authentication failed or was absent. |
| 403 Forbidden | "I know who you are, and you still may not." Authorization failed. |
The names are historically confusing — 401 should have been "Unauthenticated". Unauthorized()
returns 401 and Forbid() returns 403, which reads backwards.
⚠️ Forbid() and Unauthorized() also invoke the authentication scheme's handlers, so a
cookie scheme redirects to the login page rather than returning a bare status
(15.3). StatusCode(403) returns the raw code
without that.
ActionResult<T> — how it works¶
It has implicit conversions from both T and ActionResult:
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(Guid id, CancellationToken ct)
{
var order = await _orders.GetAsync(id, ct);
if (order is null) return NotFound(); // ✓ implicit conversion from ActionResult
return order; // ✓ implicit conversion from T → 200 OK
}
Returning order directly produces a 200 with the serialised object — the same as Ok(order),
with less noise.
⚠️ The conversions confuse the ternary operator, because C# cannot pick a common type between
NotFoundResult and OrderDto:
// ✗ Does not compile
return order is null ? NotFound() : order;
// ✓ Be explicit on both branches
return order is null ? NotFound() : Ok(order);
That compile error catches people out and the fix is not obvious.
How it actually works — status codes matter¶
⚠️ Getting these wrong is a real API design problem, because clients branch on them (10.3):
// ✗ 200 with an error body — the client's success path runs
return Ok(new { error = "Order not found" });
// ✓ The status code carries the meaning
return NotFound();
// ✗ 204 has NO body — the object is silently discarded
return NoContent(); // after computing something the caller needed
// ✓ 200 when there is something to return
return Ok(result);
NoContent() discarding a body silently is worth knowing — it produces a client that receives
nothing and no error explaining why.
The deeper detail — minimal APIs and TypedResults¶
Minimal APIs use Results and TypedResults instead
(10.12):
// Results — returns IResult, the type is not visible
app.MapGet("/orders/{id:guid}", async (Guid id, IOrderService orders, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } order
? Results.Ok(order)
: Results.NotFound());
// TypedResults — the concrete types appear in the signature
app.MapGet("/orders/{id:guid}", async Task<Results<Ok<OrderDto>, NotFound>>
(Guid id, IOrderService orders, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } order
? TypedResults.Ok(order)
: TypedResults.NotFound());
TypedResults is preferable for two reasons: OpenAPI infers both the 200 and 404 responses
without [ProducesResponseType] attributes, and tests can assert on the concrete type rather than
casting.
The Results<T1, T2> union type declaring both outcomes is the part that makes it work.
Testing action results¶
[Fact]
public async Task Get_returns_NotFound_for_a_missing_order()
{
var service = Substitute.For<IOrderService>();
service.GetAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((Order?)null);
var controller = new OrdersController(service, NullLogger<OrdersController>.Instance);
var result = await controller.Get(Guid.NewGuid(), CancellationToken.None);
Assert.IsType<NotFoundResult>(result.Result); // note: .Result on ActionResult<T>
}
⚠️ With ActionResult<T> the result object is on .Result, not the value itself — .Value
holds the T when you returned one. Checking the wrong property is a common source of confusing
test failures.
Code¶
A realistic controller covering the common outcomes:
[ApiController]
[Route("api/[controller]")]
public class OrdersController(IOrderService orders) : ControllerBase
{
[HttpGet("{id:guid}", Name = "Orders_Get")]
[ProducesResponseType<OrderDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<OrderDto>> Get(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
return order is null ? NotFound() : Ok(order);
}
[HttpPost]
[ProducesResponseType<OrderDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<OrderDto>> Create(
CreateOrderRequest request, CancellationToken ct)
{
var result = await orders.CreateAsync(request, ct);
if (!result.IsSuccess)
{
// A ProblemDetails body, so errors are shaped consistently — see 10.8
return Problem(
title: "Order could not be created",
detail: result.Error,
statusCode: StatusCodes.Status400BadRequest);
}
// 201 with a Location header, URL generated from the route name — see 8.6
return CreatedAtRoute("Orders_Get", new { id = result.Value.Id }, result.Value);
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await orders.DeleteAsync(id, ct);
return result.Status switch
{
DeleteStatus.Deleted => NoContent(), // 204 — nothing to return
DeleteStatus.NotFound => NotFound(), // 404
DeleteStatus.Shipped => Conflict(new ProblemDetails
{
Status = StatusCodes.Status409Conflict,
Title = "Cannot delete a shipped order"
}),
_ => throw new UnreachableException()
};
}
}
Three deliberate choices:
ActionResult<T> where there is a success type, IActionResult where the outcomes have no
single shape.
[ProducesResponseType] for every outcome, so the OpenAPI document tells clients what to
expect rather than only documenting the happy path.
A switch expression over a result enum, rather than exceptions for expected outcomes —
"shipped orders cannot be deleted" is a normal business outcome, not an exceptional one
(1.20).
Interview questions¶
Q: What is the difference between IActionResult and ActionResult<T>?
IActionResult lets an action return any result — a 200, a 404, a redirect — but the success type
is invisible, so OpenAPI and clients cannot see what a successful response contains without an
attribute. ActionResult<T> does the same and also documents the success type, and it has
implicit conversions so you can return the object directly for a 200 or an action result for
anything else. For APIs I would default to ActionResult<T>, since it gives both flexibility and
a discoverable contract.
Q: Why does an action return a result object rather than writing the response?
Because it separates deciding from doing. The action returns a description of what should happen —
a NotFoundResult, an ObjectResult — and the framework executes it afterwards in a separate
result-execution step. That is what makes actions unit testable: you can call the method and
assert on the type of the returned result without any HttpContext, HTTP pipeline or serialization.
Q: What is the difference between 401 and 403, and between Unauthorized() and Forbid()?
401 means "I do not know who you are" — authentication failed or was absent. 403 means "I know who
you are and you still may not" — authorization failed. The names are historically confusing, since
401 is called Unauthorized when it really means unauthenticated. Unauthorized() returns 401 and
Forbid() returns 403. One subtlety is that both invoke the authentication scheme's handlers, so
under cookie authentication Forbid() redirects to an access-denied page rather than returning a
bare status — StatusCode(403) returns the raw code if that is what you want.
Q: What is TypedResults and why prefer it in minimal APIs?
It returns concrete result types rather than the general IResult, so a handler declared as
Results<Ok<OrderDto>, NotFound> states both possible outcomes in its signature. That gives you
two things: OpenAPI infers both responses without needing [ProducesResponseType] attributes, and
tests can assert on the concrete type instead of casting. Results.Ok(...) still works and is
fine, but TypedResults carries more information for no extra effort.
Traps ⚠️¶
return order is null ? NotFound() : order;does not compile. The ternary cannot find a common type — be explicit withOk(order).NoContent()discards any body silently. UseOk(result)when there is something to return.- Returning 200 with an error body means the client's success path runs.
- With
ActionResult<T>, the result object is on.Result, not.Value. Tests check the wrong one constantly. Forbid()andUnauthorized()invoke the auth scheme, so cookie auth redirects rather than returning a status.- Returning
Talone means you cannot return a 404 without throwing. - Missing
[ProducesResponseType]leaves OpenAPI documenting only the happy path. View()requiresController, notControllerBase.
Related¶
- 9.2 Controllers — where these helpers come from
- 9.1 The MVC pattern — why results are descriptions
- 10.3 Status codes — choosing the right one
- 10.8 ProblemDetails — consistent error bodies
- 10.9 OpenAPI — what
[ProducesResponseType]feeds - 10.12 Minimal APIs —
ResultsandTypedResults - 8.6 Link generation —
CreatedAtRoute - 20.6 Unit-testing controllers — asserting on results