Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 52 ยท Routing and Minimal APIs

Responses, Results and Content Negotiation

Return the right HTTP response from minimal API handlers: Results and TypedResults helpers, union return types, JSON options, files, streams and content negotiation.

A handler's return value is the response. Return a string and you get text/plain. Return an object and you get JSON. But real APIs need more: a 201 Created with a Location header, a 404 with a problem description, a file download, a stream of data that arrives piece by piece. For all of these, ASP.NET Core uses one idea: handlers return an IResult, an object that knows how to write itself to the response.

This lesson shows the built-in result helpers, the difference between Results and TypedResults, how typed union return types make endpoints self-documenting and testable, how to control JSON output, how to send files and streams, and what content negotiation means in minimal APIs.

What the return value turns into

The framework looks at the runtime type of what your handler returns:

You return Response
string 200, text/plain
IResult whatever the result writes (status, headers, body)
void or Task 200 with an empty body
any other object (record, list, number, IEnumerable<T>) 200, JSON via System.Text.Json
IAsyncEnumerable<T> JSON array, streamed item by item
flowchart LR
    H["Handler returns a value"] --> Q{"Type?"}
    Q -- "IResult" --> R["result.ExecuteAsync(httpContext)"]
    Q -- "string" --> T["text/plain body"]
    Q -- "other object" --> J["JSON body"]
    R --> W["Status, headers, body written"]
    T --> W
    J --> W

After the handler returns, the framework picks how to write the value. Every path ends with the response being written.

Results: the factory of IResult

The static class Results has a method for each common response. Most return a plain IResult.

C# The common Results helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study the output: Results.Problem produces application/problem+json (the standard error format you will use throughout Error Handling and Problem Details), Results.Created sets the Location header, and a bare string stays text/plain. Use Results.Json(value, options) when you need to override serialization for a single response.

TypedResults and union return types

Results.Ok(x) returns the broad IResult interface. TypedResults.Ok(x) returns the concrete Ok<T> type. At first that looks like a tiny difference, but it unlocks two things:

  1. Unit tests can assert on the returned object (result.Value, result.StatusCode) without running a server.
  2. Metadata about the possible responses can be discovered from the method's signature, so OpenAPI documents are generated correctly (OpenAPI and Versioning).

When a handler can return different outcomes, declare them with the union type Results<T1, T2, ...> (up to six). The compiler then checks that you only return those types.

C# TypedResults and a union return type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last two lines show why testers like TypedResults: Ok<Product> exposes StatusCode and Value as properties, so a unit test can call the handler as an ordinary method and assert on those. The returned Results<Created<Product>, ValidationProblem> is a wrapper that holds exactly one of the declared results; the framework unwraps it.

Prefer TypedResults in new code and Results<...> unions for endpoints with more than one outcome. Use plain Results when you want a quick, one-off response and do not care about metadata.

JSON options for the whole app

Object results are serialized with System.Text.Json using web defaults: camelCase names, case-insensitive reading, numbers written as numbers. You change these globally in one place with ConfigureHttpJsonOptions, which affects every minimal API response and request body.

C# Global JSON options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first response uses snake_case, writes the enum as text and omits the null property. The second passes its own options to Results.Json, which replaces (not merges with) the global ones for that response, so it is camelCase, indented, and the enum is written as the number 0. Serialization has its own lesson: JSON Serialization in APIs.

Files and streams

Large or binary responses should not be built as one big string. Three helpers cover the usual needs:

  • Results.File(bytes, contentType, fileDownloadName) sends bytes and, with a name, adds Content-Disposition: attachment so browsers save the file.
  • Results.Stream(stream, contentType) copies a Stream to the response in chunks and disposes it afterward.
  • Results.File(path, ...) or TypedResults.PhysicalFile(...) serve a file from disk.

When a handler returns an IAsyncEnumerable<T>, the framework writes a JSON array incrementally, so the client can start reading before the producer is finished. You can also write to HttpResponse.Body yourself for formats such as plain text lines.

C# A file download, a stream and an async sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The file response carries the right content type and attachment disposition, the countdown arrives as the JSON array [3,2,1] and the manual writer produced three lines. Remember the response start rule from HttpContext, Request and Response: once the first byte of the body is sent, you can no longer change the status code or headers, so set them before you write.

Content negotiation, honestly

In MVC controllers, content negotiation means the server looks at the Accept header and picks a formatter (JSON, XML, ...). Minimal APIs do not do this: object results are always JSON, and Accept is ignored. That is a deliberate simplification, since almost every modern client wants JSON.

When you do need to vary the format, read the header yourself and return the matching result:

C#
app.MapGet("/greeting", (HttpRequest request) =>
    request.Headers.Accept.ToString().Contains("text/plain")
        ? Results.Text("Hello")
        : Results.Json(new { message = "Hello" }));

For more than two formats, or for XML, MVC's formatters or a small custom IResult are the better tools. Writing your own IResult is easy: implement ExecuteAsync(HttpContext) and write the response there, which is how libraries add formats such as CSV or PDF.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A minimal API handler returns new { id = 5 } (an anonymous object). What does the client receive?

    Any returned object that is not a string or an IResult is serialized to JSON by System.Text.Json and sent with status 200.
  2. 2. What is the main advantage of TypedResults.Ok(x) over Results.Ok(x)?

    TypedResults returns concrete result types that expose StatusCode and Value and carry response metadata, while Results returns the opaque IResult interface.
  3. 3. What does the return type Results<Ok<Product>, NotFound> express?

    Results<T1, T2> is a union: the handler returns one of the declared result types, which also documents the possible responses.
  4. 4. A client sends Accept: application/xml to a minimal API endpoint that returns an object. What happens by default?

    Minimal APIs always write object results as JSON and ignore Accept. If you need other formats, check the header yourself or use MVC formatters.
  5. 5. Why should you set the status code and headers before writing the response body?

    HTTP sends the status and headers before the body. After the first body bytes are flushed, changing them throws or is ignored.

Summary

  • A handler's return value becomes the response: strings are text, other objects are JSON, and IResult values write themselves.
  • Results.* helpers cover 200, 201, 204, 400, 404, problem details, redirects, content, files and streams.
  • TypedResults.* returns concrete types that are easy to test and documented in OpenAPI; Results<T1, T2, ...> declares several possible outcomes.
  • ConfigureHttpJsonOptions sets JSON behavior app-wide, and Results.Json(value, options) overrides it for one response.
  • IAsyncEnumerable<T> streams a JSON array; Results.File and Results.Stream send binary data without building it in memory.
  • Minimal APIs always produce JSON for objects; negotiate formats yourself when you must.

Next: Endpoint Filters