ASP.NET Core — Cheat Sheet

Tags: csharp, dotnet, aspnetcore, backend, api, webdev

Level: intermediate

TL;DR: Modular web framework based on Kestrel, unified middleware pipeline, and built-in dependency injection for high-performance APIs and web apps.

Key concepts

Kestrel is the default cross-platform, asynchronous event-driven web server.

The request pipeline is configured using middleware chained via Use and Run.

Middleware order strictly determines request execution and reverse response flow.

Built-in IoC container supports Transient, Scoped, and Singleton service lifetimes.

WebApplicationBuilder unifies host configuration, DI registration, and logging.

Minimal APIs reduce boilerplate by binding endpoints directly using lambda expressions.

Routing maps incoming HTTP requests to endpoints using pattern matching and constraints.

Model binding maps query strings, route values, and request bodies to C# objects.

Model validation executes data annotations automatically before action body runs.

Configuration merges appsettings.json, environment variables, and command-line arguments.

Typical questions and ready answers

Q: What is the difference between Transient, Scoped, and Singleton service lifetimes?R: Transient creates a new instance every time it is injected. Scoped creates one instance per client HTTP request lifecycle. Singleton creates a single instance on first resolution and shares it across the entire application runtime.

Q: How does middleware execution order work in ASP.NET Core?R: Middleware executes in the order it is registered via app.Use.... Each component inspects or mutates the incoming request, calls next(), and processes the response on the reverse path.

Q: What is a "captive dependency" and how do you prevent it?R: It happens when a service with a longer lifetime captures one with a shorter lifetime, like injecting a Scoped service into a Singleton. I avoid it by enabling scope validation in development via CreateDefaultBuilder or ValidateScopes = true.

Q: How do Minimal APIs differ from traditional Controller-based APIs?R: Minimal APIs avoid controller overhead and action filters, defining route endpoints directly on WebApplication via lambdas, which reduces memory footprint and startup time.

Pitfalls and common mistakes

Injecting a Scoped service (like DbContext) into a Singleton service causes memory leaks and concurrency issues.

Placing app.UseAuthorization() before app.UseAuthentication() prevents identity claims from populating.

Calling .Result or .Wait() on asynchronous methods causes thread-pool starvation and deadlocks.

Using Run instead of Use terminates the pipeline early without calling downstream middleware.

Forgetting to register endpoint routing (app.UseRouting()) before endpoint execution middleware.

Snippets and commands

# Create a new ASP.NET Core Web API project
dotnet new webapi -n NexaApi -f net8.0

# Add package reference
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

C#

// Program.cs: Pipeline, DI registration, and Minimal API
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api/users/{id:int}", async (int id, IUserRepository repo) =>
{
    var user = await repo.GetByIdAsync(id);
    return user is not null ? Results.Ok(user) : Results.NotFound();
});

app.Run();

To review

[ ] Pipeline middleware order (UseCors, UseRouting, UseAuth)

[ ] Built-in service lifetimes and captive dependency checks

[ ] Endpoint filters in Minimal APIs

[ ] Configuration providers and Options pattern (IOptions<T>, IOptionsSnapshot<T>)

[ ] Asynchronous request handling and cancellation tokens

References

Microsoft Learn: Overview of ASP.NET Core

Microsoft Learn: ASP.NET Core Middleware

Microsoft Learn: Dependency injection in ASP.NET Core

Jarvis Interviews
Jarvis