ASP.NET Core APIs Fundamentals: Building Modern Web APIs with .NET 11

ASP.NET Core APIs Fundamentals: Building Modern Web APIs with .NET 11

13+

Build WarehouseApi with .NET 11: HTTP contracts, validation, EF Core, JWT authorization, versioning, tests, and containers.

0 followers
28 chapters
Software & AI Development
2026
You're viewing a limited preview. Create a free account to read free books or get Premium to unlock the entire library.

Chapter 1: Introduction to ASP.NET Core APIs

What You Will Learn

  • Explain statelessness and resource-based API design
  • Choose HTTP methods and status codes
  • Trace requests through Kestrel, middleware, and endpoints
  • Identify products, warehouses, and orders as resources
  • Create, run, and call a Minimal API endpoint
  • Inspect handler values at a breakpoint

Prerequisites

No additional prerequisites beyond those listed in About This Book.

Concept Overview

REST constrains API design through client-server separation, statelessness, cacheability, a uniform interface, and layering. A uniform interface identifies resources by URI and exchanges representations, here JSON. Products use SKUs, warehouses use codes, and orders use IDs. Statelessness requires each request to carry what the server needs, so any API instance can process it.

HTTP methods state intent: GET reads, POST processes content and often creates a resource, PUT replaces a resource, PATCH changes part of it, and DELETE removes it. Status codes report outcomes: 200 success, 201 creation, 404 missing resource, and 409 conflict, such as insufficient stock.

Never make a client parse a body to learn whether a request succeeded.

Kestrel, ASP.NET Core's web server, runs inside the application and can serve production traffic directly. An optional reverse proxy, such as Nginx or Azure Front Door, handles TLS termination, compression, load balancing, and filtering. Kestrel sends requests through middleware that can inspect, change, or answer them. Routing selects an endpoint; parameter binding supplies values such as the warehouse code.

Minimal APIs map a handler, a lambda or method, directly on the application. Controllers group actions in a class. This book uses Minimal APIs for focused inventory queries and health checks, then introduces a controller in Chapter 7 for orders whose actions share dependencies and status rules.

Figure 1.1. Kestrel accepts requests directly or through a reverse proxy. Middleware routes each request to a Minimal API handler or controller action.

Step-by-Step Implementation

In Visual Studio, choose File > New > Project > ASP.NET Core Web API > Next. Name the project WarehouseApi, select Next, and set Additional information as follows (Figure 1.2), then Create:

  • Framework: .NET 11
  • Authentication type: None
  • Configure for HTTPS and Enable OpenAPI support: selected (Chapter 9 uses the OpenAPI package)
  • Use controllers and Do not use top-level statements: cleared
  • Every other option: leave it as it is

Figure 1.2. Authentication and endpoint options on Additional information, set for Minimal APIs with top-level statements. Choose .NET 11 in the Framework selector above this area.

VS Code alternative: run dotnet new webapi --name WarehouseApi --framework net11.0 in the parent folder, then open WarehouseApi. The project contains Program.cs, WarehouseApi.http, both appsettings files, Properties/launchSettings.json, and WarehouseApi.csproj. Chapter 2 continues this project.

All C# listings in this chapter belong in Program.cs. Put Steps 1 to 3 below the template code: top-level statements must precede type declarations. Step 4 replaces the template statements.

Step 1: Define the Resource Contract

Create the warehouse response contract. A positional record class provides value equality and init-only properties. This immutability is shallow: a mutable list stored in a record remains mutable.

public record WarehouseSummary(
    string Code,
    string Name,
    string Location,
    bool IsOperational,
    int TotalStockItems
);

These five properties form the warehouse response contract. Keep that contract separate from storage so persistence fields do not become part of the public API.

Step 2: Define the Service Abstraction

Add an interface for warehouse queries, so the endpoint depends on a capability rather than an implementation:

public interface IWarehouseService
{
    Task<WarehouseSummary?> GetSummaryAsync(string warehouseCode);
}

GetSummaryAsync returns null for an unknown warehouse. It is asynchronous although this version reads memory, so the contract already fits later database access.

Step 3: Implement the Service

WarehouseService reads two simulated warehouses, MAIN and WEST, from a static dictionary. Chapter 4 replaces this demonstration; Chapter 10 introduces a database:

public class WarehouseService : IWarehouseService
{
    // Simulated data store, created once and only read afterward
    private static readonly Dictionary<string, WarehouseSummary> Warehouses =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["MAIN"] = new WarehouseSummary(
                "MAIN",
                "Main Distribution Center",
                "Chicago, IL",
                true,
                15420),
            ["WEST"] = new WarehouseSummary(
                "WEST",
                "West Coast Facility",
                "Phoenix, AZ",
                true,
                8320)
        };

    public Task<WarehouseSummary?> GetSummaryAsync(string warehouseCode)
    {
        if (string.IsNullOrWhiteSpace(warehouseCode))
        {
            return Task.FromResult<WarehouseSummary?>(null);
        }

        Warehouses.TryGetValue(warehouseCode, out var summary);
        return Task.FromResult(summary);
    }
}

The comparer makes MAIN and main the same facility. Built once and never modified, the dictionary is safe for concurrent reads.

Step 4: Configure the Application

Delete everything the template put in Program.cs, keep your types from Steps 1 to 3, and type these top-level statements above them:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IWarehouseService, WarehouseService>();

var app = builder.Build();

Dependency injection supplies a handler's declared services from registered implementations. AddSingleton registers one WarehouseService for the application lifetime; Chapter 3 explains other lifetimes. Map the endpoint and start the app:

app.MapGet("/api/warehouses/{code}", async (string code, IWarehouseService service) =>
{
    var summary = await service.GetSummaryAsync(code);
    return summary is null ? Results.NotFound() : Results.Ok(summary);
});

app.Run();

Keep the types below these statements. Binding takes code from {code}; the dependency injection container supplies IWarehouseService. Results.NotFound returns 404, and Results.Ok returns 200 with JSON.

The URI identifies a warehouse; its representation and status describe the result.

The template chooses random ports. In Properties/launchSettings.json, set each applicationUrl port to 5080 for http or 7080 for https. Set WarehouseApi.http's first line to @WarehouseApi_HostAddress = http://localhost:5080. Select http in Visual Studio's start list, then Debug > Start Without Debugging (Ctrl+F5). Alternatively, run dotnet run in the folder holding WarehouseApi.csproj. The console must show Now listening on: http://localhost:5080. On first use, Visual Studio may request trust for the development HTTPS certificate or Hot Reload's IIS Express certificate, even with http selected. Accept that local certificate prompt before continuing.

Open WarehouseApi.http from Solution Explorer. Replace the template's OpenAPI and weather requests, which now return 404, with these requests separated by ###. Accept requests JSON. VS Code uses the REST Client extension:

GET {{WarehouseApi_HostAddress}}/api/warehouses/MAIN
Accept: application/json

###

Add equivalent entries for main and UNKNOWN. Select Send request above MAIN (Figure 1.3). A browser at http://localhost:5080/api/warehouses/MAIN also runs this GET. MAIN and main return:

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

{
    "code": "MAIN",
    "name": "Main Distribution Center",
    "location": "Chicago, IL",
    "isOperational": true,
    "totalStockItems": 15420
}

/api/warehouses/UNKNOWN returns 404 Not Found with no body.

Figure 1.3. Body shows the status, JSON, and Content-Type. Headers lists all headers; Raw shows the unformatted exchange.

Step 5: Debug the Endpoint

A breakpoint pauses execution for inspection. Stop the app with Ctrl+C in its console. Click the left margin beside var summary = await service.GetSummaryAsync(code);, or press F9 on it. Start with Debug > Start Debugging (F5), then send MAIN.

Execution stops before the line runs. Open Debug > Windows > Locals: code is "MAIN", service is a WarehouseService, and summary is null. F10 (Step Over) runs the call. Expand summary: Name is "Main Distribution Center" and TotalStockItems is 15420 (Figure 1.4). Hovering also shows a data tip. F5 continues to the 200 response. Remove the breakpoint with F9 on its line and stop with Shift+F5. In VS Code with C# Dev Kit, F5 starts debugging; Run and Debug contains Variables, Watch, and Call Stack.

Figure 1.4. After F10, Locals shows the bound code, injected service, and returned MAIN warehouse.

The HTTP editor times out after 20 seconds. If inspection takes longer, continue with F5 and resend MAIN; continue the retry within 20 seconds.

Full Example

The complete Program.cs uses the Web SDK's implicit namespaces, so it needs no using directives.

Program.cs

// Application configuration
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IWarehouseService, WarehouseService>();

var app = builder.Build();

// API endpoints
app.MapGet("/api/warehouses/{code}", async (string code, IWarehouseService service) =>
{
    var summary = await service.GetSummaryAsync(code);
    return summary is null ? Results.NotFound() : Results.Ok(summary);
});

app.Run();

// Domain contract
public record WarehouseSummary(
    string Code,
    string Name,
    string Location,
    bool IsOperational,
    int TotalStockItems
);

// Service abstraction
public interface IWarehouseService
{
    Task<WarehouseSummary?> GetSummaryAsync(string warehouseCode);
}

// Service implementation
public class WarehouseService : IWarehouseService
{
    // Simulated data store, created once and only read afterward
    private static readonly Dictionary<string, WarehouseSummary> Warehouses =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["MAIN"] = new WarehouseSummary(
                "MAIN",
                "Main Distribution Center",
                "Chicago, IL",
                true,
                15420),
            ["WEST"] = new WarehouseSummary(
                "WEST",
                "West Coast Facility",
                "Phoenix, AZ",
                true,
                8320)
        };

    public Task<WarehouseSummary?> GetSummaryAsync(string warehouseCode)
    {
        if (string.IsNullOrWhiteSpace(warehouseCode))
        {
            return Task.FromResult<WarehouseSummary?>(null);
        }

        Warehouses.TryGetValue(warehouseCode, out var summary);
        return Task.FromResult(summary);
    }
}

The other files, in the companion folder Chapter01/WarehouseApi:

  • WarehouseApi.http: the three warehouse requests from Step 4
  • WarehouseApi.csproj, Properties/launchSettings.json, and both appsettings files: the template's files, with launch profiles on ports 5080 (http) and 7080 (https)

Keep data access out of endpoint code.

Keep this endpoint independent of storage so Chapter 10 can replace memory with a database.

Common Mistakes

  • Confusing HTTP with REST. Use resource URIs and stateless requests; HTTP alone does not enforce REST.
  • Keeping sessions in memory. Clients become tied to one instance, memory grows with shoppers, and new instances cannot serve existing carts. Carry request context in a token or store carts as database resources with their own URIs.
  • Returning 200 for everything. Use 404 for missing resources and 201 for creation so clients can interpret the status.
  • Returning database entities. Response contracts hide persistence details and avoid entity serialization problems.
  • Ignoring edge protection. Configure TLS, connection limits, and request-size limits on internet-facing Kestrel, or use a proxy. Application authorization remains necessary.

Performance and Production Considerations

Chapter 10's database services use Scoped lifetimes because DbContext is not thread-safe; never share one across concurrent requests.

Kestrel permits 30,000,000-byte request bodies by default. Set a lower limit for the API's small adjustment and order requests to limit memory use; Chapter 5 introduces [RequestSizeLimit].

Configure Kestrel's limits explicitly before production.

A TLS-terminating proxy hides the client's address and original scheme until forwarded headers are configured in Chapter 16.

Summary

You built a stateless warehouse endpoint with a resource URI, JSON response, and precise status. Kestrel runs the middleware, routing chooses the handler, and dependency injection supplies its service.

Key Terms

  • REST: API design constrained by resources, statelessness, caching, layering, and a uniform interface
  • Uniform interface: Resource URIs and representation-based operations
  • Statelessness: Each request supplies its required context
  • Kestrel: ASP.NET Core's web server
  • Reverse proxy: A server handling edge traffic before Kestrel
  • Middleware pipeline: Components that inspect, modify, or answer requests
  • Minimal APIs: Handlers mapped directly on the application
  • Resource: Information identified by a URI
  • Status code: The request's three-digit outcome
  • Route parameter: A value bound from a URL segment
  • Breakpoint: A line where debugging pauses execution

Mini Quiz

1. A client requests a warehouse code that does not exist. Which status code should the API return?

A. 200 OK

B. 400 Bad Request

C. 404 Not Found

D. 500 Internal Server Error

2. A PUT request to /api/products/SKU-123 carries a complete JSON representation. What does it ask the server to do?

A. Update only the fields that the body includes

B. Replace the stored product with the one sent

C. Create the product only if the SKU is new

D. Delete the product, then create a new one

3. Program.cs calls AddSingleton<IWarehouseService, WarehouseService>(), and the handler declares an IWarehouseService service parameter. What does the handler receive on each request?

A. The one WarehouseService instance the container created for the application's lifetime

B. A new WarehouseService that the framework creates for each request

C. Null, because the handler never calls new WarehouseService()

D. A WarehouseSummary that the framework deserializes from the request body

4. Two Warehouse API instances run behind a load balancer. One keeps a client's identity in memory, and the client's next request reaches the other, which knows nothing about it. Which REST constraint did the design break?

A. Cacheability

B. Layered System

C. Uniform Interface

D. Statelessness

5. Which responsibilities does a reverse proxy in front of the Warehouse API typically take on?

A. TLS termination, compression, and request filtering at the edge

B. Matching request URLs to the application's endpoint handlers

C. Serializing the endpoint results to JSON for each client

D. Resolving the services that endpoint handlers need

6. In app.MapGet("/api/warehouses/{code}", async (string code, IWarehouseService service) => ...), what binds "MAIN" in /api/warehouses/MAIN to code?

A. Dependency injection

B. Route parameter binding

C. JSON body deserialization

D. Query string binding

Answers are provided in the Answer Key at the end of the book.

Activity

  • Create a Web API project named ProductApi that targets .NET 11, with File > New > Project in Visual Studio or dotnet new webapi --name ProductApi --framework net11.0
  • Add a ProductSummary record with Sku, Name, UnitPrice (decimal), and IsActive properties
  • Create an IProductService interface with Task<ProductSummary?> GetBySkuAsync(string sku)
  • Implement it with at least two simulated products in a dictionary with case-insensitive keys
  • Register the service with AddSingleton
  • Map /api/products/{sku} to return the product as JSON, or 404 when it does not exist
  • Run the application (Ctrl+F5, or dotnet run) and test both cases: 200 with a Content-Type that starts with application/json and the product's properties, and 404 for an unknown SKU

Enjoying this book?

Create a free account to leave comments, track your progress, and more!

Read and listen on the go with the unQbd app. Get the app
An unhandled error has occurred. Reload đŸ—™

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please reload the page.