Tags: web-dev reference

Reference - ASP.NET Core

Language: ASP.NET Core 10.0 (.NET 10, LTS)
Checked: 2026-10-30


One long-running process. A host builds a dependency-injection (DI) container and a configuration tree once, at startup; then every request walks an ordered middleware pipeline and ends at an endpoint. Minimal APIs, controllers, Razor Pages and Blazor are four ways of writing that endpoint — the pipeline underneath is the same.


The language, the SDK, the dotnet CLI, .csproj, NuGet and async/await itself are in Reference - C Sharp and Async in C Sharp. This note is what ASP.NET Core adds on top. Reference - Umbraco is a CMS built on this — everything here applies inside it.

Versioning, in one line: .NET ships every November; even numbers are LTS (long-term support, 3 years), odd are STS (standard-term support, 2 years). ASP.NET Core’s version always equals the .NET version. At the check date .NET 10 is current LTS, .NET 11 is at release candidate, and .NET 8 and 9 both leave support on 2026-11-10.

§0 The one idea

A host builds two things once — a service container and a configuration tree — and then every request flows through an ordered pipeline of middleware until something produces a response.

STARTUP (once)                          EVERY REQUEST

WebApplication.CreateBuilder(args)      Kestrel accepts the connection
  ├─ configuration  (json, env, args)     ↓
  ├─ logging                            HttpContext created
  └─ builder.Services  ← register         ↓  a DI scope opens
          ↓                             middleware 1  ──┐
builder.Build()     ← container frozen  middleware 2  ──┤ each can act before
          ↓                             middleware 3  ──┤ AND after the next
app.UseX() …        ← pipeline order      ↓             │
app.MapX() …        ← endpoints         endpoint        │
          ↓                               ↓             │
app.Run()           ← blocks; serves    response unwinds back up
                                          ↓  scope disposed

Three ideas carry the whole framework:

  • Dependency injection (DI) — classes ask for what they need in their constructor (or handler parameters), and a container built at startup supplies it. You never new up a database context or a logger. Not a library you add: the framework itself is assembled this way, and AddControllers(), AddAuthentication(), AddDbContext() are all just service registrations
  • Configuration — one merged key/value tree built from JSON files, environment variables, secrets and command-line arguments, with a fixed precedence. Read through DI, not process.env
  • Middleware pipeline — ordered functions, each receiving the request and a next. Order is the order you wrote them in Program.cs, and it’s load-bearing

vs Express: the pipeline is the same idea — app.Use((ctx, next) => …) is app.use((req, res, next) => …) with await. What Express leaves to you, ASP.NET Core makes first-class: DI (Express has none; you import modules), configuration (Express has process.env and whatever dotenv you bolt on), logging, auth, validation, OpenAPI (the standard machine-readable API description — §12). Express is a router with a middleware chain; ASP.NET Core is that plus an application framework. Reference - Express

vs Next: Next on Vercel is effectively serverless — each request may hit a fresh, short-lived function, so nothing survives between requests and you design for statelessness. ASP.NET Core is one long-lived process serving thousands of concurrent requests on a thread pool. Consequences: in-memory caches and singletons genuinely persist; startup cost is paid once; and anything you put in a singleton is shared across every user at once, which is where the DI-lifetime bugs come from. Next also owns the UI; ASP.NET Core can render UI (Razor Pages, MVC views, Blazor) or just be the API a Next front end calls — §12. Reference - Next.js

What’s language and what’s framework. Most of the “magic” is C#:

Looks like magicActually
app.MapGet("/", () => "hi")a lambda passed to a method — C#
[Authorize], [HttpGet], [Required]attributes — metadata the framework reads by reflection or a source generator
handler parameters filled in by nameframework: parameter binding reads the lambda’s signature
builder.Services.AddX()C# extension methods on IServiceCollection — each package adds its own
no Main methodC# top-level statements — the compiler generates Main
no using linesimplicit usings from the Web SDK — <ImplicitUsings>enable</ImplicitUsings>
.cshtml / .razor filesframework: the Razor compiler turns them into C# classes at build time

The request lifecycle

The order middleware must go in, per Microsoft’s guidance, for a Razor Pages/MVC app:

request
  ↓
Kestrel                    the built-in HTTP server, in-process
  ↓
ExceptionHandler / HSTS    catch everything below it; prod only
                           (HSTS = HTTP Strict Transport Security header)
  ↓
HttpsRedirection           http → https
  ↓
Static files               serve wwwroot; short-circuits on a hit
                           (.NET 9+ templates: MapStaticAssets, an endpoint)
  ↓
Routing                    MATCH the endpoint — doesn't run it yet
  ↓
CORS                       cross-origin resource sharing;
                           needs to know the endpoint's policy
  ↓
Authentication             who are you? sets HttpContext.User
  ↓
Authorization              are you allowed? reads endpoint metadata
  ↓
(Antiforgery, RateLimiter, Session, ResponseCaching …)
  ↓
Endpoint                   RUN the matched handler
  ↓
response travels back up through every layer, in reverse

Routing is split in two. UseRouting selects the endpoint and attaches it to the request; the endpoint executes at the end. Everything between can read which endpoint was chosen — that’s how UseAuthorization knows the endpoint carries [Authorize], and how CORS knows its policy. Put auth before routing and it has nothing to inspect.

WebApplication adds some of this for you. In Development it adds the developer exception page first; it adds UseRouting at the start if you don’t call it and have endpoints; it adds UseAuthentication/UseAuthorization after routing if those services are registered and you didn’t call them; and it adds the endpoint terminal at the end. Templates still call them explicitly, which is clearer — the rule worth remembering is that explicit calls fix the position.


1. The smallest working form

This is a complete ASP.NET Core application.

// Program.cs
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello");
app.Run();

Plus the project file, which is what makes it a web app:

<!-- Hello.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

dotnet run, open the URL it prints. Sdk="Microsoft.NET.Sdk.Web" is the switch — it references the whole ASP.NET Core shared framework, so there’s no package to install for any of §1–§9. dotnet new web generates exactly this (with CreateBuilder, below).

Create vs CreateBuilder — equivalent until you need to register anything. CreateBuilder gives you the builder stage where services and config are set up. Every real app uses it:

var builder = WebApplication.CreateBuilder(args);
// builder.Services.Add…   ← registration happens here
var app = builder.Build();
// app.Use… / app.Map…     ← pipeline happens here
app.Run();

The two-phase split is the thing to internalise: builder.Services is mutable before Build() and frozen after. app exists only after. Registering a service after Build() is a compile error, not a runtime surprise — there’s no builder object holding it.

2. Routing and binding

var app = WebApplication.Create(args);
 
app.MapGet("/products/{id:int}", (int id) => $"Product {id}");
//                     ↑ route constraint   ↑ bound by NAME from the route
 
app.MapGet("/search", (string q, int page = 1) => $"{q} p{page}");
//                     ↑ not in the route → query string: /search?q=hat&page=2
 
app.MapPost("/products", (Product p) => Results.Created($"/products/{p.Id}", p));
//                        ↑ complex type on a POST → JSON body
 
app.Run();
 
record Product(int Id, string Name, decimal Price);

Binding is inferred from the parameter, in roughly this order: route value with that name → query string for simple types → body (JSON) for complex types → a registered service → special types (HttpContext, CancellationToken, ClaimsPrincipal). Override with attributes when the guess is wrong: [FromRoute], [FromQuery], [FromHeader], [FromBody], [FromForm], [FromServices].

vs Express: no req.params.id and no parseInt — int id is the parse. A non-integer id fails the :int constraint and the route doesn’t match (404); a missing required query value returns 400 before your code runs.

Route groups — the express.Router() equivalent:

var products = app.MapGroup("/api/products");   // prefix once
products.MapGet("/", () => …);
products.MapGet("/{id:int}", (int id) => …);
products.MapPost("/", (Product p) => …);
// anything chained on the group (.RequireAuthorization(), .WithTags())
// applies to every endpoint in it

Return types. Return a plain object and it’s serialised to JSON with 200. Return Results.X / TypedResults.X to choose the status:

app.MapGet("/products/{id:int}", Results<Ok<Product>, NotFound> (int id, Catalogue c) =>
    c.Find(id) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound());
//  ↑ the union return type is what OpenAPI reads to document 200 AND 404

Results.Ok(p) and TypedResults.Ok(p) produce the same response — equivalent at runtime. TypedResults carries the type into the signature, so OpenAPI and unit tests can see it. Prefer it.

Concepts: Routing for how framework routers compare.

3. Dependency injection

Register in the builder phase, receive in a constructor or handler parameter.

var builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddSingleton<IClock, SystemClock>();
//                            ↑ ask for this   ↑ get this
var app = builder.Build();
 
app.MapGet("/time", (IClock clock) => clock.Now);
//                    ↑ not route/query/body → resolved from the container
app.Run();
 
interface IClock { DateTimeOffset Now { get; } }
class SystemClock : IClock { public DateTimeOffset Now => DateTimeOffset.UtcNow; }

In a class, it arrives through the constructor. C# 12 primary constructors make this one line — a language feature, not DI magic:

public class OrderService(IClock clock, ILogger<OrderService> log)
{
    public Order Place(Cart c) { log.LogInformation("Placing at {T}", clock.Now); … }
}
// registration:  builder.Services.AddScoped<OrderService>();

Why an interface: swap SystemClock for a FakeClock in tests, or a Redis cache for an in-memory one in Development, by changing one registration line. Registering a concrete class with no interface is fine when you’ll never swap it.

Lifetimes

LifetimeOne instance per…Use for
AddSingletonthe whole process, foreverstateless helpers, caches, HttpClient factories, config snapshots
AddScopedrequest (one DI scope per request)anything holding per-request state — DbContext above all
AddTransientevery time it’s asked forlightweight, stateless, cheap to build

vs Next/serverless: “singleton” in a serverless function is accidentally per-instance and might vanish; here it is genuinely one object shared by every concurrent request. It must be thread-safe.

The captive dependency

A longer-lived service holding a shorter-lived one keeps it alive past its lifetime.

builder.Services.AddSingleton<PriceCache>();           // lives forever
builder.Services.AddScoped<AppDbContext>();            // meant to live one request

class PriceCache(AppDbContext db) { … }                // ← captive

request 1   → PriceCache created → grabs DbContext #1
request 2   → same PriceCache    → still DbContext #1   ← shared across requests
request 500 → same PriceCache    → still DbContext #1   ← not thread-safe, stale
                                                          change tracker, leaks

The rule: a service may only depend on services that live at least as long as it does. Singleton → singleton only. Scoped → scoped or singleton. Transient → anything.

In Development the container checks this (ValidateScopes is on in the Development environment) and throws at startup or first resolve — “Cannot consume scoped service … from singleton”. In Production it’s off, so the bug that throws locally is silent in prod if it only surfaces on a path you didn’t exercise. The fix when a singleton genuinely needs scoped work: inject IServiceScopeFactory and create a scope per operation.

Keyed services register several implementations of one interface under names — AddKeyedSingleton<IPayment, StripePayment>("stripe"), received with [FromKeyedServices("stripe")]. Optional; most apps never need them.

4. Configuration

One merged tree, read through DI. CreateBuilder assembles it from these sources, later wins:

1. appsettings.json                    committed; defaults
2. appsettings.{Environment}.json      committed; per-env overrides
3. User secrets                        Development ONLY; outside the repo
4. Environment variables               the deploy-time override
5. Command-line args                   highest
// appsettings.json
{
  "Logging": { "LogLevel": { "Default": "Information" } },
  "ConnectionStrings": { "Shop": "Server=localhost;Database=shop;…" },
  "Checkout": { "FreeShippingThreshold": 50, "Currency": "GBP" }
}

Keys are paths joined by :. Checkout:Currency. Environment variables can’t contain : on every OS, so they use a double underscore: Checkout__Currency=EUR overrides the JSON. That one convention is how every container and App Service setting reaches your code.

The environment is ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT). Unset means Production — which is why a fresh deploy without the variable is production-shaped, and why local runs get Development from Properties/launchSettings.json. app.Environment.IsDevelopment() branches on it. Concepts: Environment Configuration, Environments.

User secrets keep dev credentials out of the repo:

dotnet user-secrets init
dotnet user-secrets set "Stripe:ApiKey" "sk_test_…"
# stored in your user profile, merged into config in Development only

Production secrets come from environment variables or a vault provider (Azure Key Vault has a configuration provider) — Secrets Management.

Reading it — three equivalent forms

// (a) raw — fine for one value
var currency = builder.Configuration["Checkout:Currency"];
 
// (b) typed section, bound once
var opts = builder.Configuration.GetSection("Checkout").Get<CheckoutOptions>();
 
// (c) the OPTIONS PATTERN — register, then inject anywhere
builder.Services.Configure<CheckoutOptions>(builder.Configuration.GetSection("Checkout"));
app.MapGet("/threshold", (IOptions<CheckoutOptions> o) => o.Value.FreeShippingThreshold);
 
public class CheckoutOptions
{
    public decimal FreeShippingThreshold { get; set; }
    public string Currency { get; set; } = "GBP";
}

All three read the same value. (c) is the idiomatic one: typed, injectable, testable, and it has variants — IOptions<T> (read once, singleton-safe), IOptionsSnapshot<T> (re-read per request, scoped), IOptionsMonitor<T> (live, with change notifications). Register with AddOptions<CheckoutOptions>().Bind(section).ValidateDataAnnotations().ValidateOnStart() instead (Configure<T> doesn’t chain) and a missing setting fails the deploy instead of the first customer.

vs Node: process.env.FREE_SHIPPING is a string, possibly undefined, read wherever. Here it’s a typed object, validated at startup, injected.

5. Middleware

Inline — the Express shape:

app.Use(async (context, next) =>
{
    var sw = Stopwatch.StartNew();
    await next(context);                                  // ← everything downstream
    context.Response.Headers["Server-Timing"] = $"app;dur={sw.ElapsedMilliseconds}";
    //  ↑ BUG if the body has started — headers are already sent. See below
});

Three verbs:

  • Use — do something, call next, optionally do something after
  • Run — terminal; never calls next. Anything registered after it is unreachable
  • Map / MapWhen / UseWhen — branch the pipeline by path or predicate

As a class — when it needs services or is reused:

public class CorrelationIdMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext ctx, ILogger<CorrelationIdMiddleware> log)
    {   //                                        ↑ per-request services go HERE, not the ctor
        var id = ctx.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? Guid.NewGuid().ToString();
        ctx.Response.Headers["X-Correlation-Id"] = id;
        using (log.BeginScope(new { CorrelationId = id }))
            await next(ctx);
    }
}
// app.UseMiddleware<CorrelationIdMiddleware>();

Conventional middleware is constructed once — it’s effectively a singleton. Scoped services injected through its constructor become captive (§3). Take them as InvokeAsync parameters instead, which are resolved per request.

Order is behaviour. Same middleware, different order, different app:

UseAuthorization();  UseRouting();     ← auth runs before an endpoint is
                                         selected; [Authorize] is never seen
UseRouting();  UseAuthorization();     ← correct

UseStaticFiles() after UseAuthorization()  ← every CSS file goes through auth
UseExceptionHandler() last                 ← catches nothing; everything above
                                             it threw first

The response can’t be changed once it has started. Headers go out with the first body byte. Setting a header after await next() works only if nothing downstream wrote yet — use context.Response.OnStarting(…) to set headers just before they’re flushed.

Built-in middleware worth knowing exists before writing your own: rate limiting (Rate Limiting), output caching and response caching (HTTP Caching), response compression, CORS, forwarded headers, request localisation, health checks (MapHealthChecks).

6. Logging

ILogger<T> is registered by default; ask for it.

app.MapPost("/orders", (Order o, ILogger<Program> log) =>
{
    log.LogInformation("Order {OrderId} placed for {Total}", o.Id, o.Total);
    //                       ↑ message TEMPLATE, not string interpolation
    return TypedResults.Accepted($"/orders/{o.Id}");
});

Write templates, not $"…". {OrderId} becomes a named, queryable property in any structured sink (Application Insights, Seq, OpenTelemetry). An interpolated string is one opaque string, and it’s built even when the level is filtered out.

Levels per category, in config:

"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning",
    "Microsoft.EntityFrameworkCore.Database.Command": "Information"
  }
}

The last line logs every SQL statement Entity Framework Core (EF Core, §10) sends — the quickest way to spot N+1 Queries. Concept: Observability.

7. Three ways to build endpoints

Equivalent forms. The same endpoint — fetch a product by id, 404 if missing — written three ways. All three run through the same pipeline, binding, DI, auth and filters; they differ in where the code lives and what conventions apply.

Minimal API — handlers mapped in code. Current default for dotnet new webapi:

app.MapGet("/api/products/{id:int}", async Task<Results<Ok<Product>, NotFound>> (int id, ShopDb db) =>
    await db.Products.FindAsync(id) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound());

Controller (Web API) — a class per resource, actions as methods, routes as attributes:

// Controllers/ProductsController.cs
[ApiController]
[Route("api/products")]
public class ProductsController(ShopDb db) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<Product>> Get(int id) =>
        await db.Products.FindAsync(id) is { } p ? p : NotFound();
}
// Program.cs:  builder.Services.AddControllers();  …  app.MapControllers();

Razor Page — a page-shaped endpoint that returns HTML: a .cshtml template plus a code-behind “page model”:

// Pages/Products/Detail.cshtml.cs
public class DetailModel(ShopDb db) : PageModel
{
    public Product Product { get; private set; } = default!;
 
    public async Task<IActionResult> OnGetAsync(int id)       // ← handler per HTTP verb
    {
        var p = await db.Products.FindAsync(id);
        if (p is null) return NotFound();
        Product = p;
        return Page();
    }
}
// Program.cs:  builder.Services.AddRazorPages();  …  app.MapRazorPages();
@* Pages/Products/Detail.cshtml *@
@page "{id:int}"
@model DetailModel
<h1>@Model.Product.Name</h1>
<p>@Model.Product.Price.ToString("C")</p>

URL is the file path: Pages/Products/Detail.cshtml + @page "{id:int}" → /Products/Detail/42. File-based routing, like Next’s app/ folder.

Minimal APIControllersRazor Pages
ReturnsJSON (or anything)JSON (or views, in MVC)HTML
RoutingMapGet in code[Route]/[HttpGet] attributesfile path + @page
GroupingMapGroupclass per resourcefolder per area
Filtersendpoint filtersaction filters, richer pipelinepage filters
Pick whenAPIs, new code, small serviceslarge APIs, teams used to MVC, needing model-binding extensibilityserver-rendered forms and pages
Express analogueapp.get(…)NestJS controllers— (Next pages)

MVC with views is the older HTML form: a controller action returns View(model), which renders Views/{Controller}/{Action}.cshtml. Same Razor syntax as Razor Pages, but routing is by controller convention rather than file. Razor Pages is the recommended starting point for page-focused apps; MVC views remain everywhere in existing codebases.

Razor syntax in six lines

@model ProductListModel                               @* the C# type this view renders *@
<h2>@Model.Title</h2>                                 @* expression, HTML-ENCODED by default *@
@foreach (var p in Model.Items) {                     @* C# control flow inline *@
    <a asp-page="/Products/Detail" asp-route-id="@p.Id">@p.Name</a>   @* tag helper → href *@
}
@Html.Raw(Model.TrustedHtml)                          @* opt OUT of encoding — cross-site scripting risk *@

Tag helpers (asp-page, asp-for, asp-route-*) are attributes the Razor compiler turns into server code — they generate URLs from routes rather than hard-coded strings, and asp-for wires a form input to a model property including its validation attributes. vs JSX: same “expressions in markup” idea, but @ instead of {}, encoding on by default, and it renders once on the server with no client runtime.

Shared layout is _Layout.cshtml with @RenderBody(); _ViewImports.cshtml holds shared @using and tag-helper registrations; _ViewStart.cshtml sets the default layout.

8. Validation and problem details

Data annotations on the model, checked automatically:

public record CreateProduct(
    [Required, StringLength(100)] string Name,
    [Range(0.01, 10_000)] decimal Price);

Where they’re enforced:

  • Controllers with [ApiController] — automatically; an invalid model returns 400 with a problem-details body before your action runs
  • Razor Pages / MVC — automatically populated into ModelState; you check if (!ModelState.IsValid) return Page(); and the form re-renders with errors. Tag helpers also emit matching client-side validation attributes
  • Minimal APIs — from .NET 10, builder.Services.AddValidation(); turns on the same attribute validation for query, header and body parameters, returning 400. It uses a source generator that only scans the assembly where AddValidation is called. Before .NET 10, Minimal APIs validated nothing — older code uses FluentValidation or an endpoint filter

Problem details (RFC 9457, formerly 7807) is the standard JSON error shape:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": { "Price": ["The field Price must be between 0.01 and 10000."] }
}

builder.Services.AddProblemDetails() plus app.UseExceptionHandler() makes unhandled exceptions and bare status codes come back in this shape too, instead of an empty body. A Next.js client then needs one error parser. Error Handling Strategies

Forms and antiforgery: Razor Pages forms include an antiforgery token automatically; Minimal API endpoints that bind [FromForm] require one. This is ASP.NET Core’s defence against cross-site request forgery (CSRF) — Common Vulnerabilities, Forms in Frameworks.

9. Authentication and authorisation

Two separate steps, two middleware — Authentication vs Authorisation.

Pick a scheme by who the client is:

CookieJWT bearer
Clientbrowser hitting this same appanother app — a Next.js server, mobile app, another API
Credentialencrypted auth cookie, set at sign-inAuthorization: Bearer <token> from an identity provider
Packagebuilt inMicrosoft.AspNetCore.Authentication.JwtBearer
Typical issuerthis app (or ASP.NET Core Identity)Entra ID, Auth0, Keycloak — via OpenID Connect

A JWT (JSON Web Token) is a signed, self-contained token; the API validates the signature and claims without a database lookup. Concepts: Sessions and Tokens, OAuth and OpenID Connect.

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Auth:Authority"];   // issuer; keys fetched from it
        o.Audience  = builder.Configuration["Auth:Audience"];    // this API's identifier
    });
 
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("staff", p => p.RequireClaim("role", "staff"));
 
// …
app.UseAuthentication();
app.UseAuthorization();
 
app.MapGet("/me", (ClaimsPrincipal user) => user.Identity!.Name).RequireAuthorization();
app.MapDelete("/products/{id:int}", …).RequireAuthorization("staff");

Equivalent forms: .RequireAuthorization("staff") on a Minimal API endpoint is [Authorize(Policy = "staff")] on a controller action or page model. [AllowAnonymous] / .AllowAnonymous() punches a hole.

Policies over roles. A policy is a named rule (claims, roles, or custom code via an IAuthorizationHandler); endpoints name the policy, so changing what “staff” means is one edit — Authorisation Models.

.NET 10 change: cookie auth now answers 401/403 instead of a login redirect for requests to API endpoints ([ApiController], JSON Minimal APIs, TypedResults). Before 10, an API behind cookie auth returned a 302 to an HTML login page, which a fetch would follow and then fail to parse.

ASP.NET Core Identity is the built-in user store (users, password hashing, two-factor, passkeys as of 10) — use it when the app owns accounts; use an external identity provider when it doesn’t. Authentication Architecture

10. EF Core essentials

Entity Framework Core (EF Core) is Microsoft’s ORM — object-relational mapper: you write C# classes and LINQ (Language Integrated Query — C#‘s query syntax over collections) queries, it writes the SQL. Separate packages; not required. The Relational Model

// Data/ShopDb.cs
public class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();      // ← a table
}
 
public class Product
{
    public int Id { get; set; }                            // ← primary key by convention
    public required string Name { get; set; }
    public decimal Price { get; set; }
}
// Program.cs — registered SCOPED: one DbContext per request
builder.Services.AddDbContext<ShopDb>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
//    ↑ provider package: Microsoft.EntityFrameworkCore.SqlServer (or Npgsql, Sqlite…)

A query — LINQ, translated to SQL, executed on await:

app.MapGet("/products", async (ShopDb db, decimal? max) =>
    await db.Products
        .Where(p => max == null || p.Price <= max)
        .OrderBy(p => p.Price)
        .Select(p => new { p.Id, p.Name, p.Price })     // ← projection: only these columns
        .AsNoTracking()                                 // ← read-only, skip change tracking
        .ToListAsync());                                // ← SQL runs HERE

Change tracking is the other half: load an entity, mutate it, call await db.SaveChangesAsync() — EF diffs what it loaded against what you changed and writes an UPDATE for the changed columns.

Migrations — schema as code, generated from the model diff:

dotnet tool install --global dotnet-ef          # once
dotnet ef migrations add AddProductPrice        # writes Migrations/…_AddProductPrice.cs
dotnet ef database update                       # applies pending migrations

Review the generated migration before applying — a rename can be emitted as drop-and-add, which loses data. Production: generate an idempotent SQL script (dotnet ef migrations script --idempotent) or a migration bundle rather than running database update from the app at startup. Database Migrations

Lazy loading is off by default, so related entities are only loaded when you .Include() them — the default protects you from N+1 Queries at the cost of surprising nulls.

Names to recognise: Dapper (micro-ORM — you write SQL, it maps rows to objects; common where EF’s SQL generation isn’t trusted).

11. Blazor’s place

Blazor is a component framework where components are written in C# (.razor files) instead of JavaScript. It’s ASP.NET Core’s answer to React — and it runs through the same pipeline as everything above, as MapRazorComponents<App>().

@* Components/Pages/Counter.razor *@
@page "/counter"
@rendermode InteractiveServer
 
<p>Count: @count</p>
<button @onclick="() => count++">+1</button>
 
@code {
    int count;
}

The render mode decides where the component runs. Current names:

ModeRunsInteractiveMechanism
Static Server (static SSR — server-side rendering)servernorenders HTML once, like a Razor Page. The default when no mode is set
Interactive Serverserveryesa persistent SignalR (WebSocket) connection — the “circuit”. Clicks travel to the server; the server diffs and sends DOM patches back
Interactive WebAssemblybrowseryesthe .NET runtime and your assemblies download as WebAssembly (WASM); runs client-side like a single-page app (SPA)
Interactive Autoserver, then browseryesstarts as Interactive Server; switches to WebAssembly on later visits once the bundle is cached

Prerendering is on by default for the interactive modes — the server renders HTML first, then the component becomes interactive. That’s hydration by another name, with the same double-execution gotcha: initialisation code runs once on the server and again when interactivity starts. Hydration

The mode is set per component or per page, so a mostly-static site can make one widget interactive — the islands idea (Islands Architecture). Registration:

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()           // only the modes you use
    .AddInteractiveWebAssemblyComponents();
// …
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode();

dotnet new blazor --interactivity Server|WebAssembly|Auto|None scaffolds it. Static SSR also gets enhanced navigation (link clicks fetch and patch the page rather than full reloads) and streaming rendering (send the shell, stream in content as async work finishes) — Framework Rendering Modes, Rendering Strategies.

What each mode costs:

  • Interactive Server — every interaction is a network round trip; every connected user holds server memory for their circuit; a dropped connection means a reconnect overlay. Fine for internal tools on a good network, wrong for a high-traffic storefront
  • Interactive WebAssembly — a large first download (the runtime), and code runs in the browser, so no secrets and no direct database access — it calls an API like any SPA
  • Static SSR — no client cost at all; not interactive

Blazor vs a JS front end (Next.js):

  • Pick Blazor when the team is C#-first, the app is an internal tool or admin UI, and sharing model and validation classes between server and client is worth more than ecosystem
  • Pick a JS front end when it’s a public, conversion-critical site — the React ecosystem (component libraries, analytics and testing tooling, experimentation SDKs, hiring) is far larger, and Interactive Server’s per-user connection and WASM’s payload are both costs a storefront feels. Then ASP.NET Core is the API — §12
  • Static SSR Blazor and Razor Pages overlap heavily. Both render HTML on the server. Razor Pages is the older, page-model shape; static SSR Blazor uses components, and lets you add interactivity per component later

12. Serving an API to a Next.js front end

The shape: ASP.NET Core owns data and business rules; Next owns rendering. Headless Architecture, Backend for Frontend.

browser ──→ Next.js server ──→ ASP.NET Core API ──→ database
   │         (server components,     ↑
   │          route handlers)        │  server-to-server: NO CORS
   └────────── fetch from client ────┘  browser-to-API:   CORS needed

CORS only matters when the browser calls the API directly. A Next server component fetching from the API is a server-to-server call; the browser never sees it, so no CORS config applies. Calls from client components do need it — CORS:

builder.Services.AddCors(o => o.AddPolicy("frontend", p => p
    .WithOrigins("https://www.example.co.uk", "http://localhost:3000")
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials()));                       // only if sending cookies
// …
app.UseCors("frontend");                         // after UseRouting, before auth

AllowAnyOrigin() with AllowCredentials() is rejected — the CORS spec forbids * with credentials.

JSON is System.Text.Json, with web defaults: camelCase property names (Price → price), case-insensitive reading. Matches what a TypeScript client expects with no config. Tweak globally:

builder.Services.ConfigureHttpJsonOptions(o =>                 // Minimal APIs
    o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
// controllers have their own:  AddControllers().AddJsonOptions(…)

The two option sets are separate — configuring one doesn’t affect the other, a common reason enum serialisation differs between endpoints. decimal serialises as a JSON number; money arrives in JavaScript as a float, so decide whether the contract uses pence integers or strings — Serialisation Formats.

OpenAPI is built in (since .NET 9; Swashbuckle was removed from the templates):

builder.Services.AddOpenApi();
// …
if (app.Environment.IsDevelopment())
    app.MapOpenApi();                    // serves /openapi/v1.json

.NET 10 generates OpenAPI 3.1 by default and can serve YAML. No UI is included — add Scalar or Swashbuckle’s UI package if you want one. The JSON is what matters for a Next front end: generate a typed TypeScript client from it (openapi-typescript, Orval, Kiota) and the API’s C# types become TypeScript types without hand-writing either. Microsoft.Extensions.ApiDescription.Server can emit the document at build time, so the client generates in continuous integration. API Design

Auth across the two: either Next holds the user’s session and forwards a JWT to the API server-side (the backend-for-frontend shape — tokens never reach the browser), or the browser calls the API with a cookie, which needs same-site domains or AllowCredentials plus careful cookie SameSite settings — Cookies.

13. Hosting and deploying

Kestrel is the HTTP server inside every ASP.NET Core app — cross-platform, in-process, fast enough to face the internet directly. IIS is not required; it’s one host option on Windows.

OPTION                         SHAPE
Kestrel alone                  app listens on :80/:443 itself
Reverse proxy → Kestrel        nginx / YARP / a load balancer terminates TLS,
                               forwards to the app on an internal port
IIS → in-process               Windows; the ASP.NET Core Module hosts the app
                               inside the IIS worker process
Container → anything           the usual answer now
Azure App Service              managed platform; Linux or Windows; config via app settings
                               (which arrive as environment variables — §4)

Behind a proxy, add forwarded headers. The app sees the proxy’s IP and http scheme otherwise — HTTPS redirection loops, generated URLs say http://, rate limiting buckets everyone as one client. app.UseForwardedHeaders() near the top of the pipeline, configured to trust the proxy. TLS and HTTPS

Containers: the SDK builds an image without a Dockerfile — dotnet publish /t:PublishContainer. Official images listen on port 8080 by default since .NET 8 (was 80) — docker run -p 8000:80 against a new image connects to nothing; override with ASPNETCORE_HTTP_PORTS. Images built by the SDK run as the non-root app user; hand-written Dockerfiles opt in with USER $APP_UID. Containers

dotnet publish -c Release                       # framework-dependent: needs the runtime installed
dotnet publish -c Release --self-contained      # bundles the runtime
dotnet publish /t:PublishContainer              # container image straight from the SDK

Names to recognise: .NET Aspire (local orchestration and service defaults for multi-service apps), YARP (Yet Another Reverse Proxy — Microsoft’s reverse-proxy library, itself an ASP.NET Core app), SignalR (real-time; what Interactive Server Blazor rides on).


Required versus optional

QuestionAnswer
Do I need Startup.cs?No. Gone from templates since .NET 6. ConfigureServices became builder.Services…; Configure became the app.Use… lines. Still works if a codebase has one
Do I need a Main method?No — top-level statements. A Program class is generated
Do I need controllers?No. Minimal APIs are complete. Controllers need AddControllers() + MapControllers()
Do I need MVC to render HTML?No — Razor Pages or Blazor static SSR
Must services be registered?Yes, anything you inject. Asking for an unregistered type throws at resolve time — or, in a handler, is mistaken for a body parameter
Must I call UseRouting?No — WebApplication adds it. Call it explicitly to control where it sits
Must I call UseAuthentication?Not if AddAuthentication was called — it’s added automatically. Explicit is clearer
Do I need EF Core?No. Any data access works — Dapper, raw ADO.NET, an HTTP API
Do I need IIS?No. Kestrel is the server; IIS is an optional Windows host
Do I need Windows?No. Linux in containers is the common production target
Do I need appsettings.json?No — config can come entirely from environment variables
Do I need interfaces for every service?No. Register the concrete class unless you’ll swap it
Do I need Swashbuckle for OpenAPI?No — Microsoft.AspNetCore.OpenApi is first-party; only a UI needs a third-party package
Do I need async?Not syntactically. In practice yes for any I/O — §Where it bites
Do I need Blazor?No. It’s one UI option among four

The kitchen sink

Every feature at once — labelled as such. Read the rungs first; this exists to show where each line goes.

var builder = WebApplication.CreateBuilder(args);
 
// ── configuration & options
builder.Services.AddOptions<CheckoutOptions>()
    .Bind(builder.Configuration.GetSection("Checkout"))
    .ValidateDataAnnotations().ValidateOnStart();
 
// ── data
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
 
// ── app services
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddScoped<OrderService>();
builder.Services.AddHttpClient<PaymentsClient>(c => c.BaseAddress = new("https://payments.internal/"));
 
// ── HTTP features
builder.Services.AddProblemDetails();
builder.Services.AddValidation();
builder.Services.AddOpenApi();
builder.Services.AddCors(o => o.AddPolicy("frontend", p => p.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod()));
builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", l => { l.PermitLimit = 100; l.Window = TimeSpan.FromMinutes(1); }));
builder.Services.AddOutputCache();
builder.Services.AddHealthChecks().AddDbContextCheck<ShopDb>();
 
// ── auth
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
builder.Services.AddAuthorizationBuilder().AddPolicy("staff", p => p.RequireClaim("role", "staff"));
 
// ── UI
builder.Services.AddRazorPages();
builder.Services.AddControllers();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
 
var app = builder.Build();
 
// ── pipeline, in order
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); }
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("frontend");
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.UseOutputCache();
 
// ── endpoints
app.MapStaticAssets();
if (app.Environment.IsDevelopment()) app.MapOpenApi();
app.MapHealthChecks("/health");
app.MapProductEndpoints().RequireRateLimiting("api");    // the group from the complete project below
app.MapControllers();
app.MapRazorPages();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
 
app.Run();

MapStaticAssets (.NET 9+) replaces UseStaticFiles in templates: it fingerprints files at build time, compresses them, and serves them with long-lived cache headers and ETags. UseStaticFiles still works.

A complete small project

A product API for a Next.js front end, plus one server-rendered admin page. Every file:

Shop/
├── Shop.csproj
├── Program.cs
├── appsettings.json
├── appsettings.Development.json
├── Properties/launchSettings.json      ← generated; sets Development locally
├── Data/ShopDb.cs
├── Services/PricingService.cs
├── Endpoints/ProductEndpoints.cs
└── Pages/
    ├── _ViewImports.cshtml
    ├── Admin.cshtml
    └── Admin.cshtml.cs

Shop.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.*" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.*" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.*" />
  </ItemGroup>
</Project>

Microsoft.EntityFrameworkCore.Design is what dotnet ef needs to read the project. Pin exact versions in real code; wildcards are here to avoid stamping a patch number.

appsettings.json

{
  "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } },
  "ConnectionStrings": { "Shop": "Data Source=shop.db" },
  "Pricing": { "VatRate": 0.20 },
  "Cors": { "Origins": [ "https://www.example.co.uk" ] },
  "AllowedHosts": "*"
}

appsettings.Development.json

{
  "Cors": { "Origins": [ "http://localhost:3000" ] }
}

Arrays merge by index, not by replacement — Origins:0 is overridden, but a longer production array would leave its later entries in place. A common surprise; use environment variables (Cors__Origins__0=…) or a single delimited string when it matters.

Data/ShopDb.cs

using Microsoft.EntityFrameworkCore;
 
namespace Shop.Data;
 
public class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
}
 
public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public int PricePence { get; set; }          // integer money — no float drift in JS
}

Services/PricingService.cs

using Microsoft.Extensions.Options;
 
namespace Shop.Services;
 
public class PricingOptions
{
    public decimal VatRate { get; set; }
}
 
public class PricingService(IOptions<PricingOptions> options)
{
    readonly decimal _vat = options.Value.VatRate;
 
    public int WithVat(int pence) => (int)Math.Round(pence * (1 + _vat), MidpointRounding.AwayFromZero);
}

Endpoints/ProductEndpoints.cs

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using Shop.Data;
using Shop.Services;
 
namespace Shop.Endpoints;
 
public record ProductDto(int Id, string Name, int PricePence, int PriceIncVatPence);
public record CreateProduct([Required, StringLength(100)] string Name, [Range(1, 1_000_000)] int PricePence);
 
public static class ProductEndpoints
{
    public static RouteGroupBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
    {
        var g = app.MapGroup("/api/products").WithTags("Products");
 
        g.MapGet("/", async (ShopDb db, PricingService pricing) =>
        {
            var rows = await db.Products.AsNoTracking().OrderBy(p => p.Name).ToListAsync();
            return rows.Select(p => new ProductDto(p.Id, p.Name, p.PricePence, pricing.WithVat(p.PricePence)));
        });
 
        g.MapGet("/{id:int}", async Task<Results<Ok<ProductDto>, NotFound>> (int id, ShopDb db, PricingService pricing) =>
            await db.Products.FindAsync(id) is { } p
                ? TypedResults.Ok(new ProductDto(p.Id, p.Name, p.PricePence, pricing.WithVat(p.PricePence)))
                : TypedResults.NotFound());
 
        g.MapPost("/", async (CreateProduct input, ShopDb db) =>
        {
            var p = new Product { Name = input.Name, PricePence = input.PricePence };
            db.Products.Add(p);
            await db.SaveChangesAsync();
            return TypedResults.Created($"/api/products/{p.Id}", p.Id);
        });
 
        return g;
    }
}

Pages/_ViewImports.cshtml

@using Shop
@namespace Shop.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Pages/Admin.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Shop.Data;
 
namespace Shop.Pages;
 
public class AdminModel(ShopDb db) : PageModel
{
    public List<Product> Products { get; private set; } = [];
 
    [BindProperty] public string Name { get; set; } = "";
    [BindProperty] public int PricePence { get; set; }
 
    public async Task OnGetAsync() =>
        Products = await db.Products.AsNoTracking().OrderBy(p => p.Name).ToListAsync();
 
    public async Task<IActionResult> OnPostAsync()
    {
        db.Products.Add(new Product { Name = Name, PricePence = PricePence });
        await db.SaveChangesAsync();
        return RedirectToPage();                   // POST-redirect-GET
    }
}

Pages/Admin.cshtml

@page
@model AdminModel
 
<h1>Products</h1>
<ul>
@foreach (var p in Model.Products) {
    <li>@p.Name — @((p.PricePence / 100m).ToString("C", new System.Globalization.CultureInfo("en-GB")))</li>
}
</ul>
 
<form method="post">                               @* antiforgery token added automatically *@
    <input asp-for="Name" />
    <input asp-for="PricePence" type="number" />
    <button>Add</button>
</form>

Program.cs

using Microsoft.EntityFrameworkCore;
using Shop.Data;
using Shop.Endpoints;
using Shop.Services;
 
var builder = WebApplication.CreateBuilder(args);
 
// services
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlite(builder.Configuration.GetConnectionString("Shop")));
builder.Services.Configure<PricingOptions>(builder.Configuration.GetSection("Pricing"));
builder.Services.AddSingleton<PricingService>();          // depends only on IOptions — singleton-safe
builder.Services.AddProblemDetails();
builder.Services.AddValidation();
builder.Services.AddOpenApi();
builder.Services.AddRazorPages();
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p
    .WithOrigins(builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? [])
    .AllowAnyHeader()
    .AllowAnyMethod()));
 
var app = builder.Build();
 
// pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();                // problem-details JSON for API errors
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
 
// endpoints
if (app.Environment.IsDevelopment()) app.MapOpenApi();
app.MapProductEndpoints();
app.MapRazorPages();
 
app.Run();

Then:

dotnet ef migrations add Initial
dotnet ef database update
dotnet run
# GET  /api/products        → JSON for Next.js
# GET  /openapi/v1.json     → generate the TS client from this
# GET  /Admin               → server-rendered page

The admin page has no auth — in a real app it gets [Authorize(Policy = "staff")] on AdminModel, or options.Conventions.AuthorizePage("/Admin", "staff") in AddRazorPages.


Where it bites

  • Middleware order. The most common silent bug. Auth before routing; CORS after auth (it belongs between them); exception handling not first; static files behind authorisation. Nothing errors; behaviour is just wrong. Read Program.cs top to bottom as the path a request takes
  • DI lifetimes. Scoped inside singleton (§3); DbContext used from two threads at once — it isn’t thread-safe, so Task.WhenAll over two queries on one context throws; a singleton holding mutable state shared by every user. Development’s scope validation catches the first one; nothing catches the others
  • Async all the way. Every I/O call should be awaited, back to the handler. .Result or .Wait() on a task blocks a thread-pool thread while it waits; under load the pool runs out of threads, requests queue, and latency climbs with CPU idle — thread-pool starvation. vs Node: in Node a blocking call stalls the one thread visibly; here it degrades gradually and looks like a slow database. async void loses exceptions. Pass the request’s CancellationToken into EF and HttpClient calls so an abandoned request stops its work. Async in C Sharp, Async Models, Concurrency and Parallelism
  • Configuration precedence. An environment variable silently beats appsettings.Production.json; user secrets only load in Development, so a value that works locally is missing in staging; ASPNETCORE_ENVIRONMENT unset means Production; arrays merge by index. When a value is wrong, the question is which source won
  • Startup.cs-era tutorials. Anything showing Startup.cs, ConfigureServices(IServiceCollection services), IWebHostBuilder, app.UseEndpoints(endpoints => …) or services.AddMvc() is from .NET 5 or earlier. It still maps one-to-one — ConfigureServices body → builder.Services, Configure body → app.Use… — but don’t copy the shape into new code. Likewise anything calling it ”.NET Core” (the “Core” was dropped from the runtime’s name at .NET 5, kept for ASP.NET Core and EF Core) or ”.NET Framework” — the Windows-only predecessor, a different, frozen runtime
  • HttpClient. new HttpClient() per request exhausts sockets; one static instance ignores DNS changes. Use AddHttpClient / IHttpClientFactory, which pools handlers correctly
  • Tracking queries everywhere. Reads without AsNoTracking() pay for change tracking they never use; large lists without .Select projection load every column
  • Two JSON option sets. Minimal APIs and controllers configure serialisation separately (§12)
  • Response already started. Setting headers or status after the body began writing throws or is ignored (§5)