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

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

13+

Build production-ready Web APIs with ASP.NET Core and .NET 10.

1 follower
26 chapters
Software & AI Development
2026

$49 a year. The paperback ships free with your first year.

Buying multiple copies? Request bulk pricing.
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

  • Articulate the five primary REST constraints (treating code-on-demand as optional) and evaluate API designs against them
  • Identify appropriate HTTP methods and status codes for common warehouse operations (inventory checks, order creation, stock adjustments)
  • Explain the ASP.NET Core 10 hosting model, including the relationship between Kestrel, the request pipeline, and middleware
  • Describe the architectural boundaries of the Warehouse inventory and order fulfillment API domain
  • Make informed initial decisions about when to use Minimal APIs versus controller-based approaches for specific endpoint types

Prerequisites

No additional prerequisites beyond those listed in About This Book.

Concept Overview

REST is an architectural style, not a protocol. Roy Fielding defined its constraints in 2000: statelessness, cacheability, uniform interface, client-server separation, layered system, and the optional code-on-demand. These constraints create scalable, evolvable systems that the Warehouse inventory and order fulfillment API implements through concrete inventory operations.

HTTP provides the protocol mechanics that make REST practical. The uniform interface constraint demands resource identification through URIs, where each resource represents a domain entity. For the Warehouse API, resources include products identified by SKU, warehouses identified by code, and orders identified by reference numbers. Manipulation happens through representations. Clients receive JSON; they never interact with database rows directly.

Statelessness means the server retains no client context between requests. Each request must contain all information necessary for processing, which enables horizontal scaling. Session state belongs in client tokens or external stores, not server memory.

HTTP methods define operation intent. GET retrieves representations, while POST creates subordinate resources or submits data for processing. PUT replaces resources entirely to enforce idempotent updates, and PATCH applies partial modifications. DELETE removes resources. Status codes communicate results: 200 indicates success, 201 confirms creation, 404 signals missing resources, and 409 indicates conflicts such as attempting to reserve stock that does not exist. Precise status codes prevent warehouse staff from parsing response bodies to determine whether stock reservations succeeded or failed.

Clients and servers negotiate representations through headers. The Accept header declares preferred response formats; Content-Type indicates the payload format. The Warehouse API uses JSON exclusively, but these headers ensure future compatibility.

ASP.NET Core 10 provides the hosting infrastructure to implement these REST patterns efficiently. Kestrel serves as the default web server, handling HTTP requests directly during development. In production, Kestrel typically runs behind a reverse proxy such as IIS, Nginx, or Azure Front Door, which handles TLS termination, compression, and request filtering.

The hosting model centers on WebApplicationBuilder, which configures services, middleware, and endpoints. The request pipeline processes incoming HTTP requests through a series of middleware components that can inspect, modify, or short-circuit the request. Routing matches request URIs to endpoint handlers. Model binding converts HTTP elements into .NET objects; in this chapter, route binding maps URL segments to parameters, while later chapters extend this to request bodies and query strings.

ASP.NET Core offers two primary endpoint authoring models. Minimal APIs use lambda expressions and top-level statements for lightweight scenarios, while controller-based APIs use classes with action methods for complex workflows requiring filters, model validation, or multiple related operations. The Warehouse API uses both intentionally: Minimal APIs handle simple inventory queries and health checks, and controllers manage order workflows with complex state transitions.

Step-by-Step Implementation

This section establishes the foundation for the Warehouse inventory and order fulfillment API. You'll create a basic ASP.NET Core 10 project structure, define domain contracts, implement a service abstraction, and expose your first endpoint for querying warehouse status.

Step 1: Define the Resource Contract

Create a record representing warehouse summary data. This type serves as the API contract between the server and clients.

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

Records provide value-based equality and immutable semantics. This suits API contracts where data transfer objects should not change after creation. The properties describe essential warehouse attributes: identification code, display name, physical location, operational status, and aggregate stock count.

Step 2: Define the Service Abstraction

Introduce an interface representing warehouse query capabilities. This abstraction enables testability and allows the implementation to evolve without affecting endpoint code.

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

The method returns a nullable WarehouseSummary, where null indicates the requested warehouse does not exist. The asynchronous signature prepares for future database operations, and even this initial in-memory implementation uses Task to maintain contract compatibility with asynchronous data access patterns.

Step 3: Implement the Service

Create a concrete implementation of the warehouse service. This version uses simulated data. Later chapters will replace this with Entity Framework Core persistence.

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

        // Simulated repository for demonstration
        var warehouses = new Dictionary<string, WarehouseSummary>(StringComparer.OrdinalIgnoreCase)
        {
            ["MAIN"] = new WarehouseSummary(
                "MAIN",
                "Main Distribution Center",
                "Chicago, IL",
                true,
                15420),
            ["WEST"] = new WarehouseSummary(
                "WEST",
                "West Coast Facility",
                "Phoenix, AZ",
                true,
                8320)
        };

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

Warehouse codes are compared using ordinal ignore case rules to ensure MAIN and main identify the same facility. The dictionary serves as a temporary data store. This approach demonstrates the service pattern without requiring database configuration in the introductory chapter.

Step 4: Configure the Application

Create the application entry point using WebApplicationBuilder, then register the service and map the endpoint.

var builder = WebApplication.CreateBuilder(args);

// Register services in the dependency injection container
builder.Services.AddSingleton<IWarehouseService, WarehouseService>();

var app = builder.Build();

// Configure the HTTP request pipeline
app.MapGet("/api/warehouses/{code}", async (string code, IWarehouseService service) =>
{
    var summary = await service.GetSummaryAsync(code);

    if (summary is null)
    {
        return Results.NotFound();
    }

    return Results.Ok(summary);
});

app.Run();

The AddSingleton registration creates one WarehouseService instance for the application lifetime. This suits the current in-memory implementation. Scoped or transient lifetimes become necessary when introducing database contexts in later chapters.

The MapGet method creates a Minimal API endpoint. The route template "/api/warehouses/{code}" includes a route parameter. ASP.NET Core binds the code segment from the URL to the string code parameter through route binding. The framework inspects the lambda parameters and resolves IWarehouseService from the built-in container, injecting it automatically at runtime.

Results.NotFound produces a 404 status code when the warehouse does not exist. Results.Ok returns 200 with the JSON representation. This implements the uniform interface constraint. The endpoint identifies a resource through the URI, manipulates it through HTTP semantics, and returns self-descriptive messages with appropriate status codes.

To test this implementation, start the application in Visual Studio using Debug > Start Without Debugging. Navigate to /api/warehouses/MAIN in a browser or API client. The following example shows the HTTP request and response:

GET /api/warehouses/MAIN HTTP/1.1
Host: localhost:5000
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

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

Requesting /api/warehouses/UNKNOWN returns a 404 status with no response body.

Full Example

The following listing consolidates the previous steps into a single Program.cs file suitable for a new ASP.NET Core Web API project. This represents the complete initial state of the Warehouse inventory and order fulfillment API.

using System.Collections.Generic;
using System.Threading.Tasks;

// 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
{
    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);
    }
}

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

var app = builder.Build();

// In production, add UseForwardedHeaders() middleware when running behind a reverse proxy
// to ensure correct scheme and client IP detection

// 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();

This implementation demonstrates separation of concerns: the record defines the contract, the interface abstracts the capability, the implementation encapsulates data access logic, and the endpoint configuration handles HTTP concerns. This layering prevents the endpoint from knowing whether data originates from memory, a database, or an external service.

The example uses Minimal APIs for the endpoint definition. This approach requires minimal ceremony. For the simple retrieval operation shown here, Minimal APIs reduce file count and cognitive load. Complex order fulfillment workflows introduced in later chapters will benefit from controller organization.

Common Mistakes

  • Confusing REST with HTTP. REST is an architectural style; HTTP is a protocol. You can build HTTP APIs that violate REST constraints. Don't treat HTTP as merely a transport mechanism for remote procedure calls. Respect resource identification and statelessness.
  • Storing session state on the server. Violating the statelessness constraint prevents horizontal scaling. Do not use in-memory session storage for API authentication state or shopping carts; instead, use client-side tokens or external distributed caches. In production, I have seen teams store shopping cart data in server memory to improve perceived performance, only to face cascading failures during traffic spikes when the session state exhausted available memory.
  • Returning incorrect status codes. Always return 404 when a resource does not exist. Return 201 for successful POST requests that create resources. Returning 200 for every response forces clients to parse bodies to determine success or failure.
  • Exposing database entities directly. Never return Entity Framework Core entity classes from API endpoints. Use dedicated DTOs or records like WarehouseSummary to prevent serialization issues, protect internal schema details, and decouple the API contract from the database structure.
  • Running Kestrel exposed to the internet without a reverse proxy. Kestrel is optimized for application logic, not edge security. Always place a reverse proxy such as IIS, Nginx, or a cloud load balancer in front of Kestrel in production to handle connection limits, request filtering, and TLS termination.
  • Mixing Minimal APIs and Controllers without strategy. Both approaches work, but mixing them arbitrarily creates inconsistency. Decide based on complexity: use Minimal APIs for simple CRUD and health checks, and use Controllers for complex workflows requiring filters, validation, or multiple related actions.

Performance and Production Considerations

The singleton service registration used in this chapter suits stateless, thread-safe services. The WarehouseService implementation uses a static readonly dictionary initialized once, making it thread-safe for concurrent reads. When introducing Entity Framework Core in Chapter 10, you'll switch to scoped lifetimes because DbContext instances are not thread-safe and must not be shared across concurrent requests.

Kestrel uses asynchronous I/O to minimize thread blocking, enabling high concurrency with moderate resource consumption. However, the default configuration targets development scenarios.

In production, configure Kestrel limits explicitly. Set maximum request body sizes appropriate for your domain. The Warehouse API will handle bulk stock adjustments; configure request limits to prevent memory exhaustion from maliciously large payloads.

Reverse proxy configuration affects performance significantly. Ensure the proxy supports HTTP/2 to enable multiplexing, and configure connection pooling between the proxy and Kestrel. In Azure deployments, use Application Request Routing or Front Door for global load balancing.

Logging configuration requires attention. The default logging verbosity produces excessive output at scale. Configure minimum log levels per environment. Information level suits development. Warning or Error level reduces overhead in production.

Summary

REST constraints, including the optional code-on-demand, create scalable, maintainable APIs through statelessness, resource identification, and uniform interfaces. HTTP provides the protocol mechanisms for these constraints, including header-based content negotiation, while ASP.NET Core 10 implements these patterns through Kestrel, a configurable middleware pipeline, and flexible endpoint models.

The Warehouse inventory and order fulfillment API begins with these foundations. You established resource contracts, service abstractions, and your first Minimal API endpoint, creating an architecture that separates HTTP concerns from domain logic to enable evolution as requirements expand.

Choose Minimal APIs for simple operations like inventory queries, and select controller-based APIs for complex order workflows. Always deploy Kestrel behind a reverse proxy in production; remember to configure forwarded headers middleware to preserve client information. Maintain statelessness to ensure horizontal scaling. These decisions form the baseline for the authentication, data access, and integration patterns covered in subsequent chapters.

Key Terms

  • REST (Representational State Transfer): Architectural style defining constraints for scalable, evolvable distributed systems
  • Uniform Interface: Constraint requiring resource identification through URIs and standardized manipulation through representations
  • Statelessness: Constraint requiring each request to contain all information necessary for processing; the server doesn't store client session state between requests
  • Kestrel: Cross-platform web server built into ASP.NET Core that handles HTTP requests
  • Reverse Proxy: Intermediary server (such as IIS, Nginx, or Azure Front Door) placed in front of Kestrel to handle TLS termination and edge security
  • Middleware Pipeline: Sequential chain of components processing HTTP requests, where each component can inspect, modify, or short-circuit the request
  • Minimal APIs: Lightweight endpoint definition approach using lambda expressions and top-level statements when you don't need the full MVC pipeline
  • Resource: Domain entity identified by a URI and represented via JSON or other formats, such as a warehouse or product
  • Status Code: Three-digit HTTP response code indicating the result of the request (200 for success, 404 for not found, etc.)
  • Route Parameter: Variable segment within a URL template (such as {code} in /api/warehouses/{code}) bound to handler method parameters

Mini Quiz

  1. Which HTTP status code is most appropriate when a client requests a warehouse code that does not exist in the system?

A. 200 OK

B. 400 Bad Request

C. 404 Not Found

D. 500 Internal Server Error

  1. A client sends a PUT request to /api/products/SKU-123 with a complete JSON representation. In the API design approach recommended by this book, what is the primary purpose of this operation?

A. To partially update specific fields of the product

B. To replace the entire resource with the provided representation

C. To create a new product only if it does not already exist

D. To delete the existing product and create a replacement

  1. Reviewing the WarehouseService implementation from Step 3, why does the code use Task.FromResult<WarehouseSummary?>(null) instead of returning null directly when the warehouse code is empty?

A. To satisfy the Task<WarehouseSummary?> return type without using async/await syntax

B. To prevent the garbage collector from collecting the null reference

C. To indicate that the operation failed rather than returned no data

D. To enable the method to run on a separate thread

  1. Which REST architectural constraint prevents the server from storing client session state between requests?

A. Cacheability

B. Layered System

C. Statelessness

D. Uniform Interface

  1. When deploying the Warehouse API to production, why should Kestrel run behind a reverse proxy?

A. To eliminate the need for HTTPS certificates in the application configuration

B. To handle TLS termination, compression, and edge security concerns

C. To enable the use of Minimal APIs instead of controller-based APIs

D. To improve Entity Framework Core query performance through connection pooling

  1. Consider the following endpoint definition from the chapter: app.MapGet("/api/warehouses/{code}", async (string code, IWarehouseService service) => ...). What mechanism binds the "MAIN" segment in the URL /api/warehouses/MAIN to the code parameter?

A. Dependency injection

B. JSON deserialization

C. Route parameter binding

D. Middleware inspection

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

Activity

  • Open Visual Studio and create a new ASP.NET Core Web API project targeting .NET 10
  • Add a new record type named ProductSummary with properties for SKU, Name, UnitPrice, and IsActive
  • Create an interface IProductService with a method Task<ProductSummary?> GetBySkuAsync(string sku)
  • Implement the interface with a class that returns simulated data for at least two products using a dictionary lookup with case-insensitive keys
  • Register the service in the dependency injection container using AddSingleton
  • Create a Minimal API endpoint at /api/products/{sku} that returns the product summary as JSON or a 404 status if not found
  • Test the endpoint using Debug > Start Without Debugging and verify both success and not-found scenarios. You'll need to inspect the response status codes (200 and 404), confirm the Content-Type header is application/json, and validate that the JSON response body contains the expected product properties for successful requests.

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.