ASP.NET Core Fundamentals: Building Modern Web Applications With .NET 10

ASP.NET Core Fundamentals: Building Modern Web Applications With .NET 10

13+

ASP.NET Core Fundamentals is a practical, modern guide to building real-world web applications using .NET 10 and ASP.NET Core.

1 follower
27 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

What You Will Learn

  • Understand the unified hosting architecture that powers ASP.NET Core applications
  • Configure application hosts using .NET 10's minimal hosting APIs and WebApplicationBuilder
  • Explain the architectural relationship between Kestrel, reverse proxies, and the request processing pipeline
  • Initialize projects using Visual Studio's template system and configure launch settings
  • Identify appropriate deployment patterns for cross-platform production environments

Prerequisites

No additional prerequisites beyond those listed in About This Book.

Concept Overview

ASP.NET Core represents a fundamental shift from previous ASP.NET frameworks. It is a cross-platform, high-performance, open-source framework for building modern web applications and services. Unlike its predecessors, ASP.NET Core unifies the programming model for web APIs, web applications, and real-time services under a single architectural approach.

This unified model simplifies application architecture.

The hosting architecture centers on Kestrel, a cross-platform web server built specifically for ASP.NET Core. Kestrel handles HTTP requests directly on Windows, Linux, and macOS. While capable of serving traffic directly to the internet, Kestrel typically operates behind a reverse proxy such as IIS, Nginx, or Apache in production environments. This arrangement provides defense against attacks, load balancing capabilities, and process management that Kestrel alone does not implement.

.NET 10 introduces refinements to the minimal hosting APIs first introduced in .NET 6. The WebApplicationBuilder and WebApplication types now provide the standard approach for configuring services, middleware, and endpoints. This model eliminates the ceremony of previous hosting configurations while maintaining full access to the underlying Generic Host infrastructure.

The request processing pipeline consists of middleware components chained together. Each component can inspect, modify, or short-circuit requests before they reach endpoint handlers. This pipeline architecture remains consistent whether you build minimal APIs or traditional controller-based applications.

Understanding when to expose Kestrel directly versus placing it behind a reverse proxy is critical for production deployments. In production, I've seen teams expose Kestrel directly to the internet without proper request limits, resulting in cascading failures during traffic spikes. Direct exposure suits containerized microservices and development environments. Reverse proxy configurations remain the standard for internet-facing applications requiring SSL termination, request filtering, or multiple application hosting on shared infrastructure.

Step-by-Step Implementation

Step 1: Create the Project

Open Visual Studio and select File > New > Project. Choose the ASP.NET Core Empty template from the project dialog. Name the solution "Chapter01Sample" and ensure the target framework is set to .NET 10.

The Empty template provides the minimal scaffolding necessary to understand the hosting model without the distraction of authentication, static files, or Razor Pages. This template generates a Program.cs file containing the essential hosting configuration.

Step 2: Examine the Generated Host Configuration

Visual Studio generates a Program.cs file containing the following structure:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

This code represents the minimal hosting API approach. WebApplication.CreateBuilder initializes a WebApplicationBuilder instance that encapsulates configuration, logging, and dependency injection services. The Build() method constructs the WebApplication instance that configures the HTTP pipeline and endpoint routing.

The MapGet method registers a minimal API endpoint that responds to HTTP GET requests at the root path. This approach eliminates the need for explicit controller classes while maintaining full access to the routing system.

Step 3: Configure the Application Builder

Modify Program.cs to demonstrate configuration patterns:

var builder = WebApplication.CreateBuilder(args);

// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.SetMinimumLevel(LogLevel.Information);

// Add services to the container
builder.Services.AddHealthChecks();

var app = builder.Build();

The WebApplicationBuilder exposes Configuration, Logging, and Services properties that correspond to the underlying Generic Host infrastructure. ClearProviders removes all logging providers, including the default debug and console providers. This allows you to configure only the providers you need, such as console logging for production scenarios.

Services are registered through the IServiceCollection exposed by builder.Services. This example adds health check services, which Chapter 16 covers in detail.

Prefer minimal logging providers in production.

Step 4: Configure Middleware and Endpoints

Extend the pipeline configuration:

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseHealthChecks("/health");

app.MapGet("/", () => new { Message = "Hello World!", Timestamp = DateTime.UtcNow });
app.MapGet("/api/status", () => Results.Ok(new { Status = "Operational" }));

app.Run();

The Environment property exposes IWebHostEnvironment for environment-specific checks. UseDeveloperExceptionPage displays detailed exception information during development; never enable this middleware in production. WebApplicationBuilder adds this middleware automatically in the Development environment, so explicit configuration is rarely necessary.

UseHttpsRedirection enforces HTTPS redirection for all requests. Middleware order matters significantly. Security headers and redirection middleware should appear early in the pipeline. Endpoint mapping typically appears last.

Step 5: Configure Host URLs and Environment

Configure launch settings through Visual Studio's project properties or the launchSettings.json file. Open Solution Explorer, expand Properties, and open launchSettings.json:

{
  "profiles": {
    "Chapter01Sample": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7001;http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

The applicationUrl property specifies the ports and protocols Kestrel will bind to during development. In production, environment variables or command-line arguments typically override these values.

Alternatively, configure URLs programmatically in Program.cs:

builder.WebHost.UseUrls("http://localhost:5000", "https://localhost:5001");

Avoid hardcoding URLs in production code. Prefer configuration providers or environment variables.

Step 6: Examine the Project File

Open the .csproj file by double-clicking the project in Solution Explorer:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

The Microsoft.NET.Sdk.Web SDK includes web-specific build targets and package references automatically. TargetFramework specifies net10.0, enabling .NET 10 language features and runtime behaviors. ImplicitUsings generates common using directives (System, System.Collections.Generic, etc.) automatically, reducing boilerplate.

Review SDK settings when upgrading projects.

Full Example

The following Program.cs demonstrates a production-ready configuration combining host settings, middleware, and endpoint mapping:

using System.Diagnostics;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Configure host settings
builder.WebHost.ConfigureKestrel(options =>
{
    options.AddServerHeader = false;
    options.Limits.MaxRequestBodySize = 10485760; // 10 MB
});

// Configure services
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

builder.Services.AddHealthChecks();

var app = builder.Build();

// Configure middleware pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseMiddleware<RequestTimingMiddleware>();

// Map endpoints
app.MapGet("/", () => Results.Redirect("/api/status"));
app.MapGet("/api/status", () => Results.Ok(new
{
    Status = "Operational",
    Environment = app.Environment.EnvironmentName,
    Timestamp = DateTime.UtcNow
}));

app.MapGet("/error", () => Results.Problem(
    statusCode: StatusCodes.Status500InternalServerError,
    title: "An error occurred while processing your request."
));

app.Run();

// Middleware implementation
public class RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();
        logger.LogInformation("Request {Method} {Path} started",
            context.Request.Method,
            context.Request.Path);

        await next(context);

        stopwatch.Stop();
        logger.LogInformation("Request {Method} {Path} completed in {ElapsedMs}ms - Status {StatusCode}",
            context.Request.Method,
            context.Request.Path,
            stopwatch.ElapsedMilliseconds,
            context.Response.StatusCode);
    }
}

This example demonstrates production-ready configuration. The Kestrel configuration removes the server header (a security best practice) and limits request body size to prevent denial-of-service attacks. JSON serialization options ensure consistent API responses.

The middleware pipeline includes conditional configuration based on environment, HTTPS redirection, and custom timing middleware that logs request duration and status codes. The endpoint mapping includes a root redirect, a status endpoint returning environment information, and a centralized error handler. This structure provides the foundation for production-ready API development.

Common Mistakes

  • Confusing WebApplicationBuilder with WebHostBuilder: Developers migrating from ASP.NET Core 2.x or 3.x sometimes attempt to use WebHost.CreateDefaultBuilder. This approach is obsolete. Use WebApplication.CreateBuilder exclusively for new .NET 10 applications. The old pattern still compiles but misses integration improvements and defaults introduced in newer hosting models.
  • Hardcoding configuration values in source code: Embedding URLs, connection strings, or feature flags directly in Program.cs creates deployment friction and security risks. Use builder.Configuration to bind environment variables, JSON files, or Azure Key Vault secrets. Keep sensitive data out of source control.
  • Misordering middleware components: Placing UseHttpsRedirection after endpoint mapping renders it ineffective. Middleware executes in registration order for incoming requests and reverse order for outgoing responses. Security headers, authentication, and HTTPS redirection must appear before endpoint mapping.
  • Exposing Kestrel directly to the internet without understanding the implications: While Kestrel is production-capable, it lacks defense against slowloris attacks, request size validation beyond basic limits, and IP restriction capabilities that reverse proxies provide. Always place Kestrel behind IIS, Nginx, or YARP for internet-facing applications unless you implement these protections explicitly.
  • Ignoring environment-specific configuration differences: Using the same logging levels, exception handling, and HTTPS policies across Development, Staging, and Production environments causes operational issues. Always verify app.Environment.IsDevelopment() or similar checks when configuring sensitive middleware.

Performance and Production Considerations

Kestrel's default configuration in .NET 10 optimizes for general-purpose workloads. For high-throughput scenarios, tune the Kestrel limits and thread pool settings. Configure the KestrelServerOptions.Limits.MaxConcurrentConnections and MaxConcurrentUpgradedConnections properties to prevent resource exhaustion during traffic spikes.

Minimal APIs reduce allocation overhead compared to controller-based architectures. The WebApplicationBuilder initializes services lazily where possible, improving startup time. However, excessive middleware registration still impacts request latency. Measure pipeline performance using the built-in EventSource events or OpenTelemetry integration discussed in Chapter 16.

When deploying behind a reverse proxy, configure forwarded headers middleware to preserve client IP addresses and protocol information. Without UseForwardedHeaders, the application sees the proxy's IP rather than the client's, breaking IP-based rate limiting and logging accuracy.

Container deployments require specific host configuration. Set the ASPNETCORE_URLS environment variable to http://+:80 or similar to bind all network interfaces. The default localhost binding prevents external access within Docker networks.

.NET 10 introduces faster startup sequences for WebApplicationBuilder through reduced reflection and optimized service provider compilation. These improvements benefit serverless and containerized scenarios where cold start time directly impacts user experience.

Summary

ASP.NET Core's hosting architecture provides a unified, cross-platform foundation for modern web development. The WebApplicationBuilder and WebApplication types introduced in recent versions, refined in .NET 10, eliminate configuration boilerplate while maintaining architectural flexibility.

Kestrel serves as the primary HTTP server, handling requests efficiently across operating systems. Production deployments typically position Kestrel behind a reverse proxy for security and operational management, though direct exposure remains valid for containerized microservices.

The request pipeline processes HTTP requests through configurable middleware components. Order matters; security and routing concerns must align with the pipeline's execution flow. Understanding these fundamentals prepares you for subsequent chapters covering middleware configuration, routing, and endpoint design. The minimal hosting model you configured in this chapter serves as the foundation for all ASP.NET Core applications, from simple APIs to complex distributed systems.

Key Terms

  • Kestrel: The cross-platform web server built specifically for ASP.NET Core that handles HTTP requests directly on Windows, Linux, and macOS.
  • Reverse Proxy: An intermediary server (such as IIS, Nginx, or Apache) that forwards client requests to Kestrel, providing SSL termination, load balancing, and security defenses.
  • WebApplicationBuilder: The configuration type that encapsulates logging, dependency injection, and host configuration for minimal hosting applications.
  • WebApplication: The configured host instance that manages the HTTP pipeline and endpoint routing.
  • Middleware Pipeline: The sequential chain of components that process HTTP requests and responses in a defined order.
  • Minimal APIs: The lightweight programming model that maps endpoints directly without requiring explicit controller classes.
  • Generic Host: The underlying infrastructure that manages application startup, lifetime, and dependency injection across .NET application types.
  • launchSettings.json: The configuration file that defines development environment variables, launch URLs, and command profiles. Don't deploy this file to production servers; it's intended for development environments only.
  • ImplicitUsings: The SDK feature that automatically generates common using directives to reduce boilerplate code.

Mini Quiz

  1. Which component serves as the primary HTTP server in ASP.NET Core applications?

A. IIS

B. Nginx

C. Kestrel

D. Apache

  1. When configuring the middleware pipeline, which statement accurately describes execution order?

A. Middleware executes in reverse registration order for incoming requests

B. Middleware executes in registration order for incoming requests and reverse order for outgoing responses

C. Endpoint mapping middleware should always appear first in the pipeline

D. UseHttpsRedirection is effective regardless of its position in the pipeline

  1. What is the primary purpose of WebApplication.CreateBuilder(args)?

A. To compile the application at runtime

B. To initialize the host with configuration, logging, and dependency injection services

C. To start the Kestrel server immediately

D. To generate the launchSettings.json file automatically

  1. In production scenarios, why should Kestrel typically operate behind a reverse proxy?

A. Kestrel does not support HTTPS certificates

B. Reverse proxies provide defense against attacks, load balancing, and process management that Kestrel lacks

C. Kestrel only runs on Windows operating systems

D. Reverse proxies are required for minimal APIs to function

  1. Which configuration approach should be preferred for setting application URLs in production environments?

A. Hardcoding URLs in Program.cs using UseUrls

B. Setting the ASPNETCORE_URLS environment variable

C. Modifying the launchSettings.json file and deploying it to production

D. Using the default localhost binding without changes

  1. What does the ImplicitUsings property in the project file enable?

A. Automatic generation of common using directives to reduce boilerplate

B. Implicit conversion between data types

C. Automatic inclusion of all NuGet packages

D. Implicit configuration of Kestrel server options

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

Activity

Extend the Chapter01Sample project to implement environment-specific middleware behavior and external configuration.

  • Open the Chapter01Sample solution in Visual Studio and navigate to Program.cs.
  • Create a new middleware class named EnvironmentLoggingMiddleware that logs the current environment name (Development, Staging, or Production) at the Information level for every request.
  • Register the middleware in the pipeline only when the application runs in the Development environment; use a conditional check with app.Environment.IsDevelopment().
  • Add a new endpoint at /api/config that returns a JSON object containing the current environment name and the URLs the application is listening on (access these through app.Urls).
  • Remove any hardcoded URL configurations from Program.cs.
  • Right-click the project in Solution Explorer and select Properties. Navigate to Debug > General > Open debug launch profiles UI.
  • In the Environment variables section, add ASPNETCORE_ENVIRONMENT with value Staging.
  • Run the application using Debug > Start Debugging (or press F5).
  • Verify that the environment logging middleware does not execute in Staging mode, and that the /api/config endpoint correctly reports "Staging" as the environment. When troubleshooting configuration issues, I've found that explicitly exposing the current environment through a diagnostic endpoint eliminates guesswork about which settings are active.
  • Stop the application. Return to the debug launch profiles UI and change the environment variable value to Development.
  • Restart the application and confirm that the middleware now logs environment information for each request.

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.