liveBook · Manning

Minimal API

As explained in .NET in Action, Second Edition

Minimal APIs are an ASP.NET Core programming model for defining HTTP endpoints with minimal ceremony and without requiring controller classes.

A minimal API defines HTTP endpoints directly in an ASP.NET Core application, without an explicit controller class. It is a compact way to turn an existing C# operation into a web service: create an empty web project, build the application, map requests to handlers, and run it. section 3.1 section 3.1.2

Map an ASCII art endpoint

`dotnet new web --name AsciiArtSvc` creates the service. In `Program.cs`, `WebApplication.CreateBuilder(args)` and `builder.Build()` set up the app; `app.MapGet("/{text}", (string text, string? font) => AsciiArt.Write(text, font))` handles a GET request. The route supplies `text`, while an optional query-string parameter supplies `font`. Call `app.Run()` to start the service. section 3.1

A handler can choose a response rather than simply returning its value. Successful requests normally receive HTTP 200; if a requested font does not exist, the handler can return `Results.NotFound()` instead of silently using the standard font. `Results.Content(...)` returns rendered text, while `Results.File(..., "image/jpeg")` can return a generated barcode image. section 3.1.2

Listing 3.16 Returning 404 if font is invalid
app.MapGet("/{text}",
  (string text, string? font) =>
    AsciiArt.Write(text, out var asciiText, font)    #1
      ? Results.Content(asciiText!)                  #2
      : Results.NotFound());                         #3

The GET handler selects either rendered ASCII art or HTTP 404 according to whether the requested font was found. section 3.1.2

How .NET in Action, Second Edition covers it

How deep it goes
Works through project creation, route and query parameters, and response selection; defers controller-based MVC.
Examples
Uses an ASCII art service with optional fonts and a barcode endpoint that returns a JPEG image.
What it assumes
Builds on console-application experience while starting web-service setup from the empty web template.
What you can do after
Build it from scratch as a small ASP.NET Core service and choose content, file, or not-found responses.
How it connects
Connects HTTP routing and query strings to C# handlers, HTTP status codes, and MVC controllers.

Also explained in

Compare how 3 books explain minimal API →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.