In an ASP.NET Core controller, why return ActionResult<T> instead of IActionResult or a plain T, and where does ActionResult<T> stop working?
answer
- plain T cannot say 404
- IActionResult hides the response type
- implicit conversion from T and ActionResult
- no implicit conversion from an interface
- null value becomes 204
basics
~20 sActionResult<T> lets one action return either the T value (200) or any ActionResult such as NotFound(), while ApiExplorer and OpenAPI still read T as the success type. Interface-typed expressions do not convert implicitly, so materialise them first.
solid answer
~40 sA plain `T` return can only produce 200 with a body (or 204 when the value is null), so it cannot express 404. `IActionResult` can return anything, but the response type disappears from ApiExplorer, so OpenAPI needs `[ProducesResponseType(typeof(ClaimDto), 200)]`. `ActionResult<T>` has two implicit conversions, from `T` and from `ActionResult`, so `return claim;` and `return NotFound();` both compile, and the success schema is inferred from `T`. Its limits: C# does not apply user-defined conversions to an interface-typed expression, so returning an `IEnumerable<T>` from a repository does not compile until you call `ToList()`; `T` itself cannot be an `IActionResult` or `IResult` type, which throws `ArgumentException`; and a null value still becomes a 204, not a 404.
code
csharp · 11 lines[HttpGet]
public async Task<ActionResult<IEnumerable<ClaimSummary>>> ListOpen(CancellationToken ct)
{
IEnumerable<ClaimSummary> open = await _store.OpenClaimsAsync(ct);
// return open; // does not compile: no user-defined conversion from an interface
return open.ToList(); // a List<T> expression can use the T -> ActionResult<T> conversion
}
[HttpPut("{id:int}/status")]
public async Task<IActionResult> SetStatus(int id, ClaimStatus status, CancellationToken ct)
=> await _store.TrySetStatusAsync(id, status, ct) ? NoContent() : NotFound();go deeper
Recall that ActionResult<T> lets an action return either the value or a helper like NotFound(), and that Ok, NotFound and NoContent mean 200, 404 and 204.
Explain the two implicit operators, how T reaches ApiExplorer, and why interface-typed expressions and null values behave the way they do.
Review signatures for null-as-204 bugs, undocumented error statuses and IEnumerable conversions, and know when TypedResults unions describe an action better.
Set a team-wide return-type convention for controllers so the OpenAPI document stays accurate without per-action attribute noise.
## Three ways to declare an action's result An ASP.NET Core controller action can declare its return type in three common ways, and each one makes a different promise to the caller and to the API description. | Return type | Can return 404/409/… | Success type visible to ApiExplorer | Typical use | |---|---|---|---| | `ClaimDto` (plain `T`) | no | yes | an action that always succeeds | | `IActionResult` | yes | no, needs `[ProducesResponseType(typeof(ClaimDto), 200)]` | actions returning several unrelated result types | | `ActionResult<ClaimDto>` | yes | yes, inferred from `T` | the default for API actions | All three can be wrapped in `Task<...>` (or `ValueTask<...>`) for asynchronous actions. ## How ActionResult<T> works `ActionResult<TValue>` is a small wrapper in `Microsoft.AspNetCore.Mvc` with two properties, `Value` and `Result`, and two **implicit operators**: - `implicit operator ActionResult<TValue>(TValue value)` wraps the value; - `implicit operator ActionResult<TValue>(ActionResult result)` wraps any MVC result such as `NotFoundResult`, `NoContentResult` or `ObjectResult`. That is why both branches of `return claim is null ? NotFound() : claim;` compile. When MVC executes the action, the wrapper's `IConvertToActionResult.Convert()` returns `Result` if one was set; otherwise it builds an `ObjectResult` for `Value` with status 200 (or with the `Status` of a `ProblemDetails` value) and the declared type `T`, and the normal output formatters write it. Because `T` is part of the signature, ApiExplorer, which feeds the built-in OpenAPI document from `AddOpenApi()`, describes the 200 response schema without an attribute. You still declare the other statuses: `[ProducesResponseType(StatusCodes.Status404NotFound)]`. ## Where it stops working 1. **Interface-typed expressions.** C# does not allow user-defined implicit conversions from an interface type, so this does not compile: ```csharp [HttpGet] public ActionResult<IEnumerable<ClaimDto>> List() => _repository.GetClaims(); // returns IEnumerable<ClaimDto> ``` The usual fixes are `return _repository.GetClaims().ToList();`, declaring `ActionResult<List<ClaimDto>>`, or `return Ok(_repository.GetClaims());`. 2. **T must be a value, not a result.** The constructors check `typeof(IActionResult).IsAssignableFrom(typeof(TValue))` and the same for `IResult`, and throw `ArgumentException` ("Invalid type parameter … specified for ActionResult<T>") for something like `ActionResult<IActionResult>`. 3. **Null is not "not found".** If `Value` is null, the `ObjectResult` holds null and `HttpNoContentOutputFormatter`, whose `TreatNullValueAsNoContent` defaults to `true`, turns the 200 into a **204 No Content**. A missing claim must be an explicit `NotFound()`. 4. **It is one success type.** When an action has two different success bodies, `ActionResult<T>` cannot describe both; use `IActionResult` with attributes, or the typed `Results<Ok<A>, Accepted<B>, NotFound>` union from `TypedResults`, which works in controllers too. ## The helper methods you return `ControllerBase` supplies factory methods that already return `ActionResult` subclasses: - `Ok()` returns 200 with no body and `Ok(value)` returns 200 with the value; `return value;` is equivalent for `ActionResult<T>`. - `NotFound()` returns 404; on an `[ApiController]` it gets a ProblemDetails body, while `NotFound(value)` sends your value. - `NoContent()` returns 204 for a successful update or delete with nothing to send back. - `BadRequest(...)`, `Conflict(...)`, `UnprocessableEntity(...)` and `Problem(...)` cover the common failure paths. ## Reviewing a signature When you review a controller action, a few questions catch most return-type defects: 1. Can this action fail in a way the caller must distinguish (missing claim, conflicting state, forbidden transition)? Then a plain `T` is wrong; use `ActionResult<T>` and return the specific helper. 2. Is every non-200 outcome documented with `[ProducesResponseType]`, so the OpenAPI document and generated clients know about the 404 or 409? 3. Could the value be null on a path that should mean "not found"? Then it must be an explicit `NotFound()`, because a null value becomes 204 and a client may treat that as success. 4. Does the action return a lazily evaluated LINQ query typed as `IEnumerable<T>`? Apart from the conversion error, materialising it inside the action keeps database access inside the action's error handling instead of during serialization. 5. Does the action really have one success shape? If not, `IActionResult` with explicit attributes or a typed `Results<...>` union describes it more honestly than `ActionResult<T>`. ## A claims API shaped this way ```csharp [HttpGet("{id:int}")] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<ClaimDto>> Get(int id, CancellationToken ct) { var claim = await _store.FindAsync(id, ct); if (claim is null) return NotFound(); return claim; // implicit ActionResult<ClaimDto> } ``` The signature tells readers and the OpenAPI document that success means a `ClaimDto`; the attribute documents the only other outcome.
- Is return Ok(claim); different from return claim; in an ActionResult<ClaimDto> action?On the wire, no: both send 200 with the serialized claim. `Ok(claim)` returns an `OkObjectResult` converted through the `ActionResult` operator, while `return claim;` goes through the `T` operator and becomes an `ObjectResult` at execution time. ApiExplorer reads `T` from the signature either way.
- When would you choose TypedResults over ActionResult<T> in a controller?When an action has several distinct success or failure shapes and you want the compiler to check them, return `Results<Ok<ClaimDto>, NotFound, Conflict<ProblemDetails>>`. The union carries its own endpoint metadata, so no `[ProducesResponseType]` is needed, but those results bypass MVC's output formatters and content negotiation.
- Returning null from an ActionResult<ClaimDto> action sends a 404 Not Found.
- IActionResult actions are left out of the OpenAPI document entirely.
- ActionResult<IEnumerable<T>> accepts any IEnumerable<T> expression, such as a LINQ query.
- ActionResult<T> needs [ProducesResponseType] for the 200 body to be documented.
- A plain ClaimDto return type can still send NotFound() when nothing is found.