TExcelTAD
Home › ASP.NET Core › Results & Status Codes

Results & Status Codes

Every HTTP response starts with a status code that tells the client what happened. Returning the right one is part of your API's contract: clients, proxies, caches and monitoring tools all react to it. In minimal APIs you control the status code (and headers and body) by returning an IResult.

Status code families

Range Meaning Common codes
2xx Success 200 OK, 201 Created, 202 Accepted, 204 No Content
3xx Redirection 301 Moved Permanently, 302 Found, 304 Not Modified
4xx The client did something wrong 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests
5xx The server failed 500 Internal Server Error, 503 Service Unavailable

The Results helpers

The static class Results creates IResult objects for every common case:

Helper Status Body
Results.Ok(value) 200 value as JSON
Results.Created(uri, value) 201 + Location header value as JSON
Results.CreatedAtRoute(name, routeValues, value) 201 + generated Location value
Results.Accepted(uri) 202 optional
Results.NoContent() 204 none
Results.BadRequest(error) 400 optional
Results.ValidationProblem(errors) 400 ProblemDetails with an errors map
Results.Unauthorized() / Results.Forbid() 401 / 403 none (handled by auth)
Results.NotFound() 404 optional
Results.Conflict(error) 409 optional
Results.Problem(detail, statusCode: …) any (default 500) ProblemDetails
Results.StatusCode(418) any none
Results.Redirect(url) 302 (or 301 with permanent: true) none
Results.Text(text, contentType) / Results.File(bytes, contentType) 200 raw content
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();       // consistent error bodies (adds traceId)
var app = builder.Build();

var books = new Dictionary<int, Book> { [1] = new(1, "Dune", 1965) };

app.MapGet("/books/{id:int}", (int id) =>
    books.TryGetValue(id, out var book) ? Results.Ok(book) : Results.NotFound());

app.MapPost("/books", (Book book) =>
{
    if (string.IsNullOrWhiteSpace(book.Title))
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["title"] = ["Title is required."]
        });
    if (books.ContainsKey(book.Id))
        return Results.Conflict(new { message = 
quot;Book {book.Id} already exists." }); books[book.Id] = book; return Results.Created(
quot;/books/{book.Id}", book); }); app.MapDelete("/books/{id:int}", (int id) => books.Remove(id) ? Results.NoContent() : Results.NotFound()); app.Run(); record Book(int Id, string Title, int Year);

Watch the status line and headers change with curl -i:

bash · try it yourself
$ curl -i -X POST localhost:5000/books -H "Content-Type: application/json" -d '{"id":2,"title":"Neuromancer","year":1984}'
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Location: /books/2
Transfer-Encoding: chunked

{"id":2,"title":"Neuromancer","year":1984}
bash · try it yourself
$ curl -s -X POST localhost:5000/books -H "Content-Type: application/json" -d '{"id":3,"title":"","year":2000}'
$ curl -s -X POST localhost:5000/books -H "Content-Type: application/json" -d '{"id":1,"title":"Dune","year":1965}'
$ curl -s -o /dev/null -w "%{http_code}\n" -X DELETE localhost:5000/books/1
$ curl -s -o /dev/null -w "%{http_code}\n" -X DELETE localhost:5000/books/1
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"title":["Title is required."]},"traceId":"00-7d3f2a9c1e8b4f60a2d5c7e9b1f3a5c7-4e6a8c0b2d4f6a8c-00"}
{"message":"Book 1 already exists."}
204
404

The second delete returns 404 because the book is already gone.

TypedResults and Results<…>

Results.Ok(...) returns the interface IResult, so the compiler (and OpenAPI) can't see which results are possible. TypedResults has the same helpers but returns concrete types such as Ok<Book> and NotFound. Combine them with the union type Results<T1, T2, …> to declare every outcome in the signature:

csharp
using Microsoft.AspNetCore.Http.HttpResults;

app.MapGet("/books/{id:int}", Results<Ok<Book>, NotFound> (int id) =>
    books.TryGetValue(id, out var book) ? TypedResults.Ok(book) : TypedResults.NotFound());

Benefits:

  • Compile-time checking — returning a Conflict from that handler is a build error.
  • Accurate OpenAPI — the generated document lists both 200 (with the Book schema) and 404.
  • Easier unit tests — call the handler and assert result.Result is Ok<Book>.

Tip: Prefer TypedResults in real projects; Results is handy for quick demos.

A result is just an object that writes the response

IResult has a single method, Task ExecuteAsync(HttpContext context). Each result type knows how to set the status code, add headers and write the body. Here is that design rebuilt in plain C#, with a fake response object instead of a real HttpContext:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;

var books = new Dictionary<int, string> { [1] = "Dune" };

IMiniResult GetBook(int id) =>
    books.TryGetValue(id, out var title) ? new OkResult(new { id, title }) : new NotFoundResult();

IMiniResult DeleteBook(int id) =>
    books.Remove(id) ? new NoContentResult() : new NotFoundResult();

foreach (var result in new[] { GetBook(1), GetBook(9), DeleteBook(1), DeleteBook(1) })
{
    var response = new FakeResponse();
    result.Execute(response);
    Console.WriteLine(response);
}

interface IMiniResult { void Execute(FakeResponse response); }

class OkResult(object value) : IMiniResult
{
    public void Execute(FakeResponse r)
    {
        r.Status = 200;
        r.ContentType = "application/json";
        r.Body = JsonSerializer.Serialize(value);
    }
}

class NotFoundResult : IMiniResult
{
    public void Execute(FakeResponse r) => r.Status = 404;
}

class NoContentResult : IMiniResult
{
    public void Execute(FakeResponse r) => r.Status = 204;
}

class FakeResponse
{
    public int Status { get; set; }
    public string? ContentType { get; set; }
    public string Body { get; set; } = "";
    public override string ToString() => 
quot;{Status} {ContentType ?? "-"} {Body}".TrimEnd(); }
200 application/json {"id":1,"title":"Dune"}
404 -
204 -
404 -

Because a result is a plain object, the decision ("which response?") is separated from the writing ("how does it go over the wire?") — that is exactly what makes TypedResults easy to test.

Choosing the right code

Situation Return
GET found the resource 200 Ok(resource)
POST created something 201 Created(location, resource)
Work queued, finished later 202 Accepted(statusUrl)
PUT/DELETE succeeded, nothing to return 204 NoContent()
Input is invalid 400 ValidationProblem(errors)
Not logged in / not allowed 401 / 403 (let the auth middleware produce them)
Resource doesn't exist 404 NotFound()
Duplicate or version conflict 409 Conflict()
Unexpected exception 500 — let the exception handler produce it

Test yourself

Which result is best after successfully creating a resource with POST?

  1. Results.Ok(item)
  2. Results.NoContent()
  3. Results.Created(
    quot;/items/{item.Id}", item)
  4. Results.Accepted()

What is the main advantage of TypedResults with a Results<Ok<Book>, NotFound> return type?

  1. Responses are smaller
  2. The possible responses are known at compile time and appear in OpenAPI
  3. It disables JSON serialization
  4. It makes the endpoint asynchronous

A DELETE succeeds and there is nothing useful to return. Which status code fits?

  1. 204 No Content
  2. 200 OK with an empty JSON object
  3. 202 Accepted
  4. 404 Not Found