skip to content

TypedResults & IResult

Returning IResult from a handler: Results vs TypedResults, the Results<Ok<T>, NotFound> union, plain objects as JSON 200 and custom IResult types. Interviewers ask why TypedResults wins.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

4

In an ASP.NET Core Minimal API, what response does a handler produce when it returns a string, a plain object, or an IResult like TypedResults.Ok?

level: juniorimportance: must knowfreq 66%

answer

  1. string: text/plain; charset=utf-8
  2. object: 200 JSON via System.Text.Json
  3. IResult: ExecuteAsync writes it
  4. null object: body is null
  5. null IResult: InvalidOperationException

basics

~10 s

A string is written as 200 text/plain, any other object is serialized to 200 application/json, and an IResult writes its own status, headers and body through ExecuteAsync; void or Task gives an empty 200.

solid answer

~40 s

The Minimal API request delegate looks at what the handler returns. A `string` is written as-is with status 200 and `text/plain; charset=utf-8`. Any other type `T` is serialized with System.Text.Json (web defaults, so camelCase) as 200 `application/json; charset=utf-8`. An `IResult`, such as `TypedResults.Ok(label)` or `TypedResults.NotFound()`, is executed through its `ExecuteAsync(HttpContext)`, so the result decides the status, headers and body. `void`, `Task` and `ValueTask` leave an empty 200. Awaitables are unwrapped first, so `Task<T>` behaves like `T`. Two edge cases matter: a `null` object is still a 200 whose body is the JSON literal `null`, and a `null` `IResult` throws `InvalidOperationException`, which surfaces as a 500.

code

http · 7 lines
http
GET /returns/999 HTTP/1.1
Host: shop.example

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

null

go deeper

for a junior

Recall the three mappings: string to text/plain, objects to JSON, IResult executes itself, all with 200 unless the result says otherwise.

for a middle

Explain why a plain object return can only express 200, and describe the null-object and null-IResult edge cases.

for a senior

Spot handlers whose return type hides a missing-resource case behind a 200 null, and standardize on typed results for anything with more than one outcome.

for a principal

Set a convention for when endpoints may return bare objects versus results, weighing brevity against explicit, documented status codes.

## Four kinds of return value When ASP.NET Core builds a Minimal API endpoint, it generates a **request delegate** around the handler. After the handler returns, that delegate turns the value into a response according to the handler's **declared return type**, after unwrapping `Task<T>` or `ValueTask<T>`: | Declared return | Status | Content-Type | Body | |---|---|---|---| | `void`, `Task`, `ValueTask` | 200 | none | empty | | `string` | 200 | `text/plain; charset=utf-8` | the string | | any other `T` | 200 | `application/json; charset=utf-8` | `T` serialized with System.Text.Json | | an `IResult` type | whatever the result sets | whatever the result sets | whatever the result writes | For a declared return type of `object`, the decision moves to run time: the delegate checks whether the returned value is an `IResult`, then whether it is a `string`, and otherwise serializes it as JSON. ## IResult: the result writes the response `IResult` (namespace `Microsoft.AspNetCore.Http`) has a single member, `Task ExecuteAsync(HttpContext httpContext)`. The built-in implementations live in `Microsoft.AspNetCore.Http.HttpResults` and are created through the static `TypedResults` and `Results` classes: - `TypedResults.Ok(value)` writes 200 and serializes `value` as JSON. - `TypedResults.NotFound()` writes 404 with no body. - `TypedResults.Conflict(error)` writes 409 with the error as JSON. - `TypedResults.NoContent()` writes 204. - `TypedResults.Created(uri, value)` writes 201, sets `Location` when a URI is given, and serializes the value. - `TypedResults.Accepted(uri)` writes 202 with `Location`. The handler only builds the object; nothing is written until the delegate calls `ExecuteAsync`, which is also why endpoint filters can inspect or replace a result before it runs. ## A returns endpoint for an electronics retailer ```csharp // 200 text/plain app.MapGet("/returns/health", () => "ok"); // 200 application/json, or 200 with the body null when nothing matches app.MapGet("/returns/{rmaId}", (int rmaId, IReturnsStore store) => store.Find(rmaId)); // The result decides: 200 with JSON, or 404 with no body app.MapGet("/v2/returns/{rmaId}", Results<Ok<ReturnRequest>, NotFound> (int rmaId, IReturnsStore store) => store.Find(rmaId) is { } rma ? TypedResults.Ok(rma) : TypedResults.NotFound()); ``` The second endpoint shows the most common surprise: returning a plain object means **200 is the only status the handler can express**. When `Find` returns `null`, the client gets 200 with the four characters `null` as the body, not a 404. The third endpoint lets the handler choose the status, which is the point of returning an `IResult`. ## Edge cases worth knowing 1. **A null `IResult`** (`IResult r = null; return r;`) is not an empty response. The delegate throws `InvalidOperationException` with "The IResult returned by the Delegate must not be null.", and the client sees a 500. 2. **`TypedResults.Ok<T>(null)`** writes 200 and **no body at all**, because the built-in results skip serialization for a null value. Compare that with returning a null `T` directly, which writes `null`. 3. **A string inside an `IResult`** is not text: `TypedResults.Ok("ok")` serializes the string as JSON, giving `"ok"` with quotes and `application/json`. Use `TypedResults.Text("ok")` for plain text from an `IResult`. 4. **A content type set earlier** wins for strings: the delegate only sets `text/plain` when no content type is present. 5. **Polymorphism.** If the runtime type differs from the declared `T` and `T` has no known polymorphism configured, the value is serialized as `object`, so the derived type's properties are written. ## Async handlers Awaitables are unwrapped before any of the rules above apply: - `Task<ReturnRequest>` behaves like `ReturnRequest`, and `Task<Results<...>>` like the union. - `Task` and `ValueTask` without a result give an empty 200 once they complete. - A handler that returns a **null `Task`** fails with "The Task returned by the Delegate must not be null.", and a `Task<IResult>` that completes with null fails with "The IResult in Task<IResult> response must not be null." Both surface as 500s. ## Choosing what to return - Return **`T`** for a handler that has exactly one outcome and always a body, such as a lookup that cannot miss. - Return a **typed result** as soon as the status depends on the data: not found, conflict, created. - Return a **`string`** only for genuinely plain-text endpoints such as a health ping. ## What interviewers listen for - The three default mappings and their content types. - That `IResult` hands control of the whole response to the result object. - That a null object gives 200 with `null`, not 404, and that a null `IResult` is a server error.

  • What is the difference between returning a null ReturnRequest and returning TypedResults.Ok<ReturnRequest>(null)?
    Both answer 200. Returning the null object directly lets the request delegate serialize it, so the body is the JSON literal `null`. `TypedResults.Ok<T>(null)` goes through the built-in result, which writes the status and skips serialization when the value is null, so the response has no body. Neither is a 404; for that the handler must return `TypedResults.NotFound()`.
  • How do you return plain text from a handler that otherwise returns IResult?
    Use `TypedResults.Text("ok")` (or `TypedResults.Content`), which writes the string with a text content type. `TypedResults.Ok("ok")` would serialize the string as JSON, quotes included, because `Ok<T>` always writes JSON. Returning a bare `string` only gives `text/plain` when the handler's declared return type is `string`.

  • Returning null from a Minimal API handler that returns an object produces a 404.
  • A returned string is serialized as a JSON string with quotes.
  • Returning a null IResult sends an empty 204 response.
  • TypedResults.Ok("ok") sends text/plain because the value is a string.
  • Minimal API handlers serialize plain objects with Newtonsoft.Json by default.
open as a page

In ASP.NET Core Minimal APIs, what is the difference between Results.Ok and TypedResults.Ok, and why is TypedResults usually the better choice?

level: middleimportance: must knowfreq 62%

basics

~20 s

Both write the same 200 JSON response; Results.Ok is declared to return IResult while TypedResults.Ok returns Ok<T>, whose static metadata documents the response, makes tests cast-free and, in ASP.NET Core 10, stops cookie authentication redirecting.

open as a page

How does a Results<Ok<ReturnLabel>, NotFound, Conflict<string>> return type work in an ASP.NET Core Minimal API handler, and what are its limits?

level: middleimportance: should knowfreq 48%

basics

~20 s

Results<T1, ..., T6> is a sealed union of two to six IResult types: each listed type converts to it implicitly, it executes whichever result was returned, and it merges every member's metadata, so 200, 404 and 409 are all documented.

open as a page

In ASP.NET Core Minimal APIs, how do you write a custom IResult that also describes its own response through IEndpointMetadataProvider?

level: seniorimportance: should knowfreq 28%

basics

~10 s

Implement IResult.ExecuteAsync to write the status, headers and body, and IEndpointMetadataProvider's static PopulateMetadata to add a ProducesResponseTypeMetadata; the metadata is used only when the handler's declared return type is your type.

open as a page