Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 52 ยท Practice and Review

ASP.NET Core Cheat Sheet

A one-page ASP.NET Core 10 cheat sheet: builder, routing, binding, results, middleware order, DI lifetimes, auth, configuration and deployment commands.

This is the quick reference for the whole ASP.NET Core tutorial. It will not teach you anything new from scratch; each row links to the lesson that explains the idea. Use it when you know what you want to do but forgot the exact spelling, the right status code, or which service lifetime to pick.

Everything assumes ASP.NET Core 10 with minimal APIs and implicit usings, as in a project created by dotnet new web. The snippets are read-only: they need the .NET SDK and the web SDK, which the in-browser runner does not have. The rest of the tutorial shows the same ideas in programs you can run here.

Program shape

C#
var builder = WebApplication.CreateBuilder(args);   // 1. builder: config, logging, DI
builder.Services.AddSingleton<IClock, SystemClock>(); // 2. register services
var app = builder.Build();                          // 3. freeze the container

app.UseExceptionHandler();                          // 4. middleware, in order
app.MapGet("/", () => "Hello");                     // 5. endpoints

app.Run();                                          // 6. start and block
Piece Purpose Learn more
WebApplication.CreateBuilder(args) Defaults: Kestrel, config providers, logging, DI The Host and the Builder
builder.Services Register services before Build() Dependency Injection
builder.Configuration / builder.Environment Settings and environment name Configuration
app.Use... Add middleware (order matters) Middleware Pipeline
app.Map... Add endpoints Minimal API Endpoints
app.Run() / await app.RunAsync() Start and wait for shutdown Your First Web App
await app.StartAsync() / StopAsync() Start without blocking (tests, tools) Your First Web App

Routing

Task Spelling
Map a verb app.MapGet, MapPost, MapPut, MapPatch, MapDelete
Several verbs app.MapMethods("/x", ["GET", "HEAD"], handler)
Route parameter "/users/{id}"
Optional parameter "/hello/{name?}"
Default value "/blog/{page=1}"
Catch-all "/files/{**path}"
Constraints {id:int}, {id:int:min(1)}, {id:guid}, {slug:alpha}, {n:range(1,10)}, {s:regex(^[a-z]+$)}
Group with prefix var api = app.MapGroup("/api/v1");
Endpoint name .WithName("GetUser") then LinkGenerator or Results.CreatedAtRoute
Metadata .WithTags("Users"), .WithSummary("..."), .Produces<T>(200)
Require auth .RequireAuthorization() or .RequireAuthorization("PolicyName")
Allow anonymous .AllowAnonymous()

A failed constraint means "no match", so the response is 404, not 400. See Route Templates and Constraints and Route Groups.

Parameter binding

Source How it is chosen Explicit attribute
Route Name appears in the template [FromRoute]
Query string Simple type not in the route [FromQuery]
Header Never inferred [FromHeader(Name = "X-Id")]
JSON body Complex type on POST/PUT/PATCH [FromBody]
Form IFormFile, IFormCollection or forms [FromForm]
Service Type registered in DI [FromServices], [FromKeyedServices("key")]
Many at once One record with properties [AsParameters]
Special types HttpContext, HttpRequest, HttpResponse, ClaimsPrincipal, CancellationToken none needed

Required parameters that cannot be bound give 400. Make a parameter optional with a default value or a nullable type. See Parameter Binding.

Results and status codes

Handler needs to send Use Status
Data TypedResults.Ok(value) or just return the value 200
New resource TypedResults.Created("/things/5", value) 201 + Location
Accepted for later TypedResults.Accepted(url) 202
Nothing to say TypedResults.NoContent() 204
Moved TypedResults.Redirect(url), RedirectPermanent 302 / 301
Bad input TypedResults.BadRequest(...), Results.ValidationProblem(errors) 400
Not signed in TypedResults.Unauthorized() 401
Not allowed TypedResults.Forbid() 403
Missing TypedResults.NotFound() 404
Conflict TypedResults.Conflict(...) 409
Stale ETag Results.StatusCode(412) 412
Too many rate limiter 429
Problem details TypedResults.Problem(detail, statusCode: 500) any
File Results.File(bytes, "image/png"), Results.Stream(...) 200
Server-sent events TypedResults.ServerSentEvents(asyncSequence) 200

Union return type for two outcomes: Results<Ok<Post>, NotFound>. See Responses and Results.

Middleware order

flowchart TD
    A["UseExceptionHandler / UseHsts"] --> B["UseHttpsRedirection"]
    B --> C["UseStaticFiles"]
    C --> D["UseRouting (implicit)"]
    D --> E["UseCors"]
    E --> F["UseRateLimiter"]
    F --> G["UseAuthentication"]
    G --> H["UseAuthorization"]
    H --> I["UseOutputCache"]
    I --> J["Endpoints"]

A sensible default order. In minimal apps routing and endpoint execution are added automatically around your calls.

Method Meaning
app.Use(async (ctx, next) => { ...; await next(); }) Middleware that may call the next component
app.Run(ctx => ...) Terminal middleware (never calls next)
app.Map("/prefix", branch => ...) Branch by path prefix
app.MapWhen(ctx => ..., branch => ...) Branch by predicate
app.UseWhen(ctx => ..., branch => ...) Conditional middleware that rejoins the pipeline
ctx.Response.OnStarting(...) Run code just before headers are sent
ctx.Response.HasStarted If true, status and headers can no longer change
ctx.Items["key"] Per-request scratch space

See Writing Custom Middleware and HttpContext.

Dependency injection

Lifetime Registration Instance lives Use for
Transient AddTransient<I, T>() Per resolve Light, stateless helpers
Scoped AddScoped<I, T>() Per request Unit of work, DbContext, per-request state
Singleton AddSingleton<I, T>() Whole app Caches, config readers, thread-safe shared state
Task Spelling
Several implementations by key AddKeyedSingleton<I, T>("key") + [FromKeyedServices("key")]
Factory registration AddScoped<I>(sp => new T(sp.GetRequiredService<X>()))
Replace a registration services.Replace(ServiceDescriptor.Singleton<I, Fake>())
Avoid captive dependency A singleton must not inject a scoped service; inject IServiceScopeFactory instead
Scope outside a request using var scope = app.Services.CreateScope();

See Dependency Injection in ASP.NET Core.

Configuration, options and logging

Task Spelling
Read a value builder.Configuration["Section:Key"] or GetValue<int>("Section:Count")
Bind a section services.Configure<MyOptions>(builder.Configuration.GetSection("My"))
Inject options IOptions<T> (fixed), IOptionsSnapshot<T> (per request), IOptionsMonitor<T> (live)
Validate at startup services.AddOptions<T>().BindConfiguration("My").ValidateDataAnnotations().ValidateOnStart()
Environment checks app.Environment.IsDevelopment(), IsProduction(), IsEnvironment("Staging")
Log logger.LogInformation("Order {Id} shipped", id) (never string interpolation)
Scope using (logger.BeginScope("Order {Id}", id)) { ... }
Filter levels "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }

Configuration precedence, lowest to highest: appsettings.json, appsettings.{Environment}.json, user secrets (Development), environment variables (Section__Key), command-line arguments. See Options, Environments and Secrets and Logging.

Authentication and authorization

Task Spelling
Add cookie auth AddAuthentication().AddCookie()
Add JWT bearer AddAuthentication().AddJwtBearer(o => o.TokenValidationParameters = ...)
Pipeline app.UseAuthentication(); app.UseAuthorization(); (in that order)
Require sign-in .RequireAuthorization() / [Authorize]
Require a role .RequireAuthorization(p => p.RequireRole("admin"))
Named policy AddAuthorization(o => o.AddPolicy("Adult", p => p.RequireClaim("age")))
Custom rule IAuthorizationRequirement + AuthorizationHandler<T>
Resource-based await authz.AuthorizeAsync(user, resource, requirement)
Everything protected by default o.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
Current user in a handler add a ClaimsPrincipal user parameter

Remember: 401 means "who are you?", 403 means "you may not". See Authentication Concepts, Cookie and JWT and Authorization.

Error handling, caching, limits and health

Task Spelling
Problem details for errors AddProblemDetails(); app.UseExceptionHandler(); app.UseStatusCodePages();
Custom exception mapping implement IExceptionHandler, AddExceptionHandler<T>()
Memory cache AddMemoryCache(), IMemoryCache.GetOrCreateAsync(key, entry => ...)
Output cache AddOutputCache(), UseOutputCache(), .CacheOutput(policy => policy.Expire(...))
Evict by tag await store.EvictByTagAsync("posts", ct)
Response compression AddResponseCompression(), UseResponseCompression()
Rate limit AddRateLimiter(...), UseRateLimiter(), .RequireRateLimiting("policy")
Health checks AddHealthChecks(), MapHealthChecks("/health/live")
CORS AddCors(...), UseCors("policy")
Static files app.UseStaticFiles() with files in wwwroot

See Error Handling, Caching and Rate Limiting and Health Checks.

Command line and deployment

Task Command
New empty web project dotnet new web -n MyApp
New API template dotnet new webapi -n MyApi
Run with hot reload dotnet watch run
Run dotnet run --urls http://localhost:5100
Add a package dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Run tests dotnet test
Create a user secret dotnet user-secrets init then dotnet user-secrets set "Api:Key" "value"
Trust the dev HTTPS certificate dotnet dev-certs https --trust
Publish (framework-dependent) dotnet publish -c Release -o ./out
Publish (self-contained) dotnet publish -c Release -r linux-x64 --self-contained -o ./out
Native AOT publish dotnet publish -c Release -r linux-x64 -p:PublishAot=true (needs CreateSlimBuilder)
Set the environment ASPNETCORE_ENVIRONMENT=Production
Set URLs ASPNETCORE_URLS=http://+:8080
EF Core migration dotnet ef migrations add Init then dotnet ef database update

A minimal container recipe:

DOCKERFILE
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "MyApp.dll"]

Behind a reverse proxy, enable forwarded headers (app.UseForwardedHeaders() with XForwardedFor and XForwardedProto) so the app sees the real client address and scheme. See Deployment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which lifetime should a service that holds per-request state (like a unit of work) use?

    Scoped services live for one request, so state is shared inside the request and never leaks across requests.
  2. 2. Which environment variable spelling sets the configuration key Logging:LogLevel:Default?

    The colon is not valid in many environment variable names, so a double underscore stands for the section separator.
  3. 3. Where should app.UseAuthorization() go relative to UseAuthentication()?

    Authorization needs the user identity that authentication produces, so authentication comes first.
  4. 4. A route is declared as {id:int}. A request arrives for /items/abc. What does the client receive?

    A failed constraint means the route does not match, so routing answers 404.

Summary

  • Four steps shape every app: create the builder, register services, build, then add middleware and endpoints.
  • Constraints narrow routes; a failed constraint is a 404. Binding picks route, query, body or services by name and type.
  • Return TypedResults for precise status codes and union return types that document every outcome.
  • Middleware order is behavior: exception handling first, authentication before authorization.
  • Scoped means per request; never inject a scoped service into a singleton.
  • 401 is "who are you", 403 is "not allowed". Publish with dotnet publish, configure with environment variables and put a proxy in front.

You have reached the end of the ASP.NET Core tutorial. Keep the cheat sheet nearby, revisit the practice exercises and interview questions whenever you want a refresher, and then build something real: the projects are the best place to start.