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

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

13+

Build the AdventureWorks web application with ASP.NET Core 11, Visual Studio, data access, authentication, tests, and diagnostics.

0 followers
29 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

What You Will Learn

  • Create the AdventureWorks project and pin the .NET 11 SDK.
  • Explain how Kestrel, middleware and endpoints answer a request.
  • Configure the host and pipeline, and run the app on fixed ports.
  • Pause a request at a breakpoint.

Prerequisites

Concept Overview

By the end of this chapter, https://localhost:7001/api/status shows {"status":"Operational","timestamp":"..."}. The app is AdventureWorks, an outdoor-gear store that every chapter extends.

A request has a method and a path, such as GET /api/status. The response has a status code: here 200 (OK), 302 or 307 (redirects to the Location header's address) or 404 (Not Found).

Kestrel, the web server built into ASP.NET Core, accepts each connection inside your app's process and hands the request to middleware: components that run in order. Each can inspect, change or end the request, and the response passes back through them in reverse. Last, an endpoint, the handler mapped to a route, writes the response (Figure 1.1). A reverse proxy, a server that forwards requests to Kestrel, is optional.

Figure 1.1. Kestrel, inside your app's process, passes each request to your middleware and endpoints. A reverse proxy in front is optional.

Step-by-Step Implementation

Step 1: Create the Project

Use a short parent folder outside synced folders such as OneDrive, for example C:\Projects; deep paths can break Windows' 260-character limit.

1. On Visual Studio's start window, choose Create a new project, search for ASP.NET Core Empty, select the C# template, and choose Next.
2. On Configure your new project, set Project name to AdventureWorks and Location to C:\Projects, keep Solution name AdventureWorks, leave Place solution and project in the same directory cleared, and choose Next.
3. On Additional information, choose Framework .NET 11.0 (Standard Term Support) and keep Configure for HTTPS, which adds an https launch profile: named local run settings in Properties/launchSettings.json. Clear Enable container support, Do not use top-level statements, Use the .dev.localhost TLD in the application URL and, if shown, Enlist in Aspire orchestration, which add files or code this app does not use. Choose Create (Figure 1.2).

Figure 1.2. The two wizard pages that shape AdventureWorks. The pictured framework selector says Preview; choose the released .NET 11 framework for your project.

4. Your working folder is now C:\Projects\AdventureWorks, holding AdventureWorks.slnx and the AdventureWorks project folder.

Add --project AdventureWorks to a command for one project. Every command in this book runs from the working folder.

5. Choose File > New > File > Text File, paste the listing, and save it in the working folder as global.json (File > Save As, type All Files, so no .txt is added). It selects the SDK for its folder and those below.
{
    "sdk": {
        "version": "11.0.100",
        "rollForward": "latestFeature"
    }
}
6. Close the solution (File > Close Solution) and reopen AdventureWorks.slnx, so it loads with that SDK.
7. In View > Terminal, dotnet --version prints 11.0.100 or a later 11.0 version; latestFeature never moves to .NET 12.

In VS Code, create and open the working folder (File > Open Folder), add global.json with New File, and run these in Terminal > New Terminal:

dotnet --version
dotnet new web --name AdventureWorks --framework net11.0
dotnet new sln -n AdventureWorks
dotnet sln add AdventureWorks

dotnet new web ends with Restore succeeded., and both routes give the same folder.

Step 2: Examine the Generated Host Configuration

The template's Program.cs:

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

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

app.Run();

CreateBuilder makes a WebApplicationBuilder, which gathers configuration, logging and services. Build returns the WebApplication, holding the pipeline and endpoints. MapGet maps GET / to a lambda, the Minimal APIs style Chapter 5 compares with controllers. app.Run() starts Kestrel.

The template made http and https profiles on random ports. Select https beside the green Start button and press Ctrl+F5 (Debug > Start Without Debugging); the browser shows Hello World! Accept any offer to trust the ASP.NET Core development certificate. In VS Code, run dotnet run --project AdventureWorks --launch-profile https, open the https address, and run dotnet dev-certs https --trust once if the browser warns.

Stop the app now. Later steps just say "Stop the app.", because a running app locks its build output and holds its port (7001 from Step 5 on):

  • Started with F5: Debug > Stop Debugging (Shift+F5).
  • Started with Ctrl+F5: close the app's console window, or press Ctrl+C in it. Shift+F5 does not stop an app started without the debugger.
  • Started from a terminal: Ctrl+C.

Step 3: Configure the Application Builder

In Program.cs, add these lines after var builder = WebApplication.CreateBuilder(args);, then a blank line:

builder.WebHost.ConfigureKestrel(options =>
{
    options.AddServerHeader = false;
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024;
});
builder.Services.AddHealthChecks();
builder.Services.AddProblemDetails();

AddServerHeader = false drops Kestrel's Server: Kestrel header. MaxRequestBodySize caps a request body at 10 MiB (default about 28.6 MiB). AddHealthChecks backs /health, and AddProblemDetails registers Problem Details, a standard JSON format for API errors. Build with Ctrl+Shift+B, or dotnet build.

Step 4: Configure Middleware and Endpoints

Right-click the AdventureWorks project, choose Add > Class, name it RequestTimingMiddleware.cs, and replace its contents. In VS Code, right-click the AdventureWorks project folder, the one that holds AdventureWorks.csproj, and choose New File.

using System.Diagnostics;

namespace AdventureWorks;

public sealed class RequestTimingMiddleware(
    RequestDelegate next,
    ILogger<RequestTimingMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        var timer = Stopwatch.StartNew();
        try
        {
            await next(context);
        }
        finally
        {
            logger.LogInformation(
                "{Method} {Path} elapsed {ElapsedMs} ms",
                context.Request.Method, context.Request.Path,
                timer.Elapsed.TotalMilliseconds);
        }
    }
}

Convention-based middleware implements no interface: the framework finds this constructor and InvokeAsync by their shape, and the HttpContext holds the request and response. The finally block logs even when later code throws, and {Method}, {Path} and {ElapsedMs} become searchable log fields.

Make using AdventureWorks; the first line of Program.cs, then a blank line, and replace everything from var app = builder.Build(); to the end with:

var app = builder.Build();
app.UseMiddleware<RequestTimingMiddleware>();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
    app.UseHsts();
}
app.UseHttpsRedirection();
app.MapHealthChecks("/health");
app.MapGet("/", () => Results.Redirect("/api/status"));
app.MapGet("/api/status", () => Results.Ok(new
{
    Status = "Operational",
    Timestamp = DateTime.UtcNow
}));
app.Run();

I keep timing first so every request gets a line, even a redirect. The host runs under an environment name: Development here, Production by default. Outside Development, UseExceptionHandler handles unhandled request exceptions without exposing stack traces. Before a response starts, it normally returns 500 and writes Problem Details when the client's Accept header allows JSON. In Development, the automatic developer exception middleware shows an HTML page to browsers and can return diagnostic Problem Details JSON to API clients. UseHsts adds HSTS (HTTP Strict Transport Security), a header telling browsers to use only HTTPS. UseHttpsRedirection sends HTTP to HTTPS.

WebApplication runs the matched endpoint after all the Use middleware, so the Use lines set the order and MapGet only registers routes. Terminal middleware ends a request without calling next, like a delegate passed to app.Run; app.Run() with no delegate starts the app.

Middleware order is behavior. Read it top to bottom.

Press Ctrl+F5 (in VS Code, the same dotnet run command). The browser lands on the JSON, and each request logs info: AdventureWorks.RequestTimingMiddleware[0] and GET / elapsed with the milliseconds.

Step 5: Configure Host URLs and Environment

Stop the app. Replace Properties/launchSettings.json with one https profile on the book's ports:

{
    "$schema": "https://json.schemastore.org/launchsettings.json",
    "profiles": {
        "https": {
            "commandName": "Project",
            "dotnetRunMessages": true,
            "launchBrowser": true,
            "applicationUrl":
                "https://localhost:7001;http://localhost:5001",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    }
}

The launch profile keeps these ports in every chapter. ASPNETCORE_ENVIRONMENT sets the environment IsDevelopment() checks. Publishing leaves this file out; a deployed app reads addresses from configuration (ASPNETCORE_URLS, --urls, ASPNETCORE_HTTP_PORTS or Kestrel:Endpoints), or Kestrel listens on http://localhost:5000. Do not add builder.WebHost.UseUrls, seen in other code.

Keep addresses out of code.

Run with Ctrl+F5, or dotnet run --project AdventureWorks. The console shows (Figure 1.3):

      Now listening on: https://localhost:7001
      Now listening on: http://localhost:5001
      Hosting environment: Development

Figure 1.3. The first run on the book's ports.

Send these GET requests from the companion's AdventureWorks/Chapter01/requests.http (File > Open > File, then Send request; VS Code needs the REST Client extension) or curl.exe (curl outside Windows PowerShell 5.1). A browser follows redirects, showing them only in F12 > Network. Visual Studio's HTTP editor also follows both redirects below and displays 200 with the status JSON. To inspect the original 302 or 307 and its Location header, use curl.exe without -L.

  • https://localhost:7001/: 302 to /api/status.
  • https://localhost:7001/api/status: 200, the status JSON.
  • https://localhost:7001/health: 200, Healthy.
  • http://localhost:5001/api/status: 307 to https://localhost:7001/api/status.
  • https://localhost:7001/missing: 404.
curl.exe -i -w "\n" https://localhost:7001/api/status
curl.exe -i -w "\n" http://localhost:5001/api/status

The 200 body, {"status":"Operational","timestamp":"2026-11-03T14:23:09.3717607Z"}, has camelCase names and no Server header.

Stop the app and run it in Production; arguments after -- go to the app and override the profile:

dotnet run --project AdventureWorks -- --environment Production

The console reports Hosting environment: Production, the routes answer as before, and the first curl.exe command shows no Strict-Transport-Security line, because UseHsts skips localhost.

Step 6: Examine the Project File

Double-click the project node (in VS Code, open AdventureWorks.csproj). The template's file stays unchanged:

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

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

</Project>

The Web SDK adds an implicit framework reference to Microsoft.AspNetCore.App, so no packages are listed. ImplicitUsings adds global usings such as Microsoft.AspNetCore.Http and Microsoft.Extensions.Logging, so RequestTimingMiddleware.cs needs only System.Diagnostics.

Step 7: Debug the Status Endpoint

Stop the app. A breakpoint pauses the app before a line runs. Click the left margin beside Status = "Operational",, or put the caret there and press F9. Visual Studio moves the red dot up to the MapGet line and highlights only Results.Ok(new { ... }), the handler body, which runs for each request.

Press F5 (Debug > Start Debugging). The browser follows the redirect, and Visual Studio pauses there with the yellow arrow while the browser waits (Figure 1.4).

Debug > Windows > Locals lists the variables in scope. This handler has none, so the list is nearly empty; Chapter 2 reads real values.

Press F5 to continue. The JSON appears, and the timing line shows a long elapsed time, because the Stopwatch ran while you were paused. Click the red dot to remove the breakpoint, and press Shift+F5.

In VS Code, set it left of the line number, press F5 (if asked, select C#, then C#: AdventureWorks; if a launch profile picker also appears, select https), and read Run and Debug > Variables.

Figure 1.4. A request paused in the /api/status handler.

Full Example

Use the project you set up in this chapter.

AdventureWorks/RequestTimingMiddleware.cs:

using System.Diagnostics;

namespace AdventureWorks;

public sealed class RequestTimingMiddleware(
    RequestDelegate next,
    ILogger<RequestTimingMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        var timer = Stopwatch.StartNew();
        try
        {
            await next(context);
        }
        finally
        {
            logger.LogInformation(
                "{Method} {Path} elapsed {ElapsedMs} ms",
                context.Request.Method, context.Request.Path,
                timer.Elapsed.TotalMilliseconds);
        }
    }
}

AdventureWorks/Program.cs:

using AdventureWorks;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
    options.AddServerHeader = false;
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024;
});
builder.Services.AddHealthChecks();
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseMiddleware<RequestTimingMiddleware>();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
    app.UseHsts();
}
app.UseHttpsRedirection();
app.MapHealthChecks("/health");
app.MapGet("/", () => Results.Redirect("/api/status"));
app.MapGet("/api/status", () => Results.Ok(new
{
    Status = "Operational",
    Timestamp = DateTime.UtcNow
}));
app.Run();

Keep Step 1 global.json and solution, Step 5 launch settings, Step 6 project file and the template appsettings files. The request file remains in the exact Chapter01 companion checkpoint.

Common Mistakes

  • Saving global.json inside the project folder, or as global.json.txt. dotnet searches the current folder and its parents, so the working folder skips it; save it beside AdventureWorks.slnx.
  • Deleting AddProblemDetails because Development works. The parameterless UseExceptionHandler needs it, so startup outside Development throws an InvalidOperationException.
  • Expecting UseHttpsRedirection to create HTTPS. Without an HTTPS endpoint it logs Failed to determine the https port for redirect and passes requests through.
  • Leaving DOTNET_ENVIRONMENT set on your machine. With WebApplication, it takes precedence over the profile's ASPNETCORE_ENVIRONMENT; check the Hosting environment line.

Performance and Production Considerations

Keep MaxRequestBodySize near the largest body a route accepts, so clients cannot send more.

The timing middleware logs one Information line per request. To silence it in Production, create AdventureWorks/appsettings.Production.json with this content:

{
    "Logging": {
        "LogLevel": {
            "AdventureWorks": "Warning"
        }
    }
}

Request.Path excludes the query string, so query tokens stay out of the log; do not log the query or body.

Hiding the Server header is not access control. Chapter 18 covers deployment settings.

Summary

AdventureWorks runs on .NET 11 with a pinned SDK, fixed ports, three routes and request timing. Chapter 2 adds the Core and Infrastructure projects, typed configuration and service lifetimes.

Key Terms

  • Kestrel: ASP.NET Core's built-in web server.
  • Middleware: a pipeline component that acts before and after the next one.
  • global.json: selects the SDK for its folder tree.
  • Launch profile: named local run settings.
  • Breakpoint: a line where the debugger pauses.

Mini Quiz

1. In Figure 1.1, which part of the AdventureWorks process accepts the HTTP connection?

A) RequestTimingMiddleware

B) Kestrel

C) The /api/status endpoint

D) The reverse proxy, which every deployment needs

2. Program.cs calls app.UseMiddleware<RequestTimingMiddleware>(); before app.UseHttpsRedirection();. You send GET http://localhost:5001/api/status. What happens?

A) The handler runs over plain HTTP and returns 200

B) Kestrel rejects the request because HSTS is on

C) The timing line is logged, and the client gets a 307

D) The client gets a 307 to HTTPS, but no timing line is logged

3. You set a breakpoint inside the /api/status handler and press F5. When does Visual Studio pause?

A) When a request for /api/status arrives

B) Once at startup, while MapGet registers the route

C) Only for direct requests, never after the redirect from /

D) As soon as the console prints Now listening on

4. Where should a published AdventureWorks get its listening addresses?

A) launchSettings.json, copied to the server with the published files

B) A builder.WebHost.UseUrls call added to Program.cs before Build

C) The random ports the template chose when it created the project

D) Configuration, such as ASPNETCORE_URLS or --urls

5. You delete builder.Services.AddProblemDetails(); and start the app in Production. What happens?

A) Nothing changes, because Production has the same services

B) Startup throws an InvalidOperationException

C) The app starts, but every request returns 500

D) The app starts, and only error responses lose their JSON

6. RequestTimingMiddleware.cs uses HttpContext and ILogger with only using System.Diagnostics;. Why does it compile?

A) ImplicitUsings adds global usings for common namespaces

B) The AdventureWorks namespace imports every framework namespace

C) Nullable enable makes the compiler skip missing usings

D) The Web SDK copies those framework types into the project

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

Activity

Work in a copy; Chapter 2 continues from your main folder.

  • Stop the app (it holds the same ports). In File Explorer, copy C:\Projects\AdventureWorks, paste it in C:\Projects, rename the copy Chapter01-Activity, and open its AdventureWorks.slnx (in VS Code, the folder).
  • Add EnvironmentLoggingMiddleware.cs with Add > Class (in VS Code, right-click the AdventureWorks project folder, the one that holds AdventureWorks.csproj, and choose New File). Model it on RequestTimingMiddleware: log Environment {Environment}, then call next. Take the name from an IHostEnvironment constructor parameter, which the framework supplies like ILogger. Check yours:
namespace AdventureWorks;

public sealed class EnvironmentLoggingMiddleware(
    RequestDelegate next,
    IHostEnvironment environment,
    ILogger<EnvironmentLoggingMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        logger.LogInformation("Environment {Environment}",
            environment.EnvironmentName);
        await next(context);
    }
}
  • After app.UseMiddleware<RequestTimingMiddleware>();, register it in a new if (app.Environment.IsDevelopment()) statement:
if (app.Environment.IsDevelopment())
    app.UseMiddleware<EnvironmentLoggingMiddleware>();
  • After the })); closing /api/status, map a diagnostic route, and keep routes like it off public servers:
app.MapGet("/api/config", () => Results.Ok(new
{
    Environment = app.Environment.EnvironmentName,
    Urls = app.Urls
}));
  • Press F5 and open /api/config: expect {"environment":"Development","urls":["https://localhost:7001","http://localhost:5001"]} and an Environment Development line per request.
  • For Staging, choose Debug > AdventureWorks Debug Properties, set ASPNETCORE_ENVIRONMENT to Staging in the https profile, and restart. In VS Code, use a PowerShell terminal:
dotnet run --project AdventureWorks -- `
    --environment Staging

/api/config reports Staging, and the Environment lines stop.

  • Set the profile back to Development, compare with the companion's AdventureWorks/Chapter01-Activity, and reopen your main AdventureWorks.slnx.

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.