Skip to main content
Quick Reference

ASP.NET Cheatsheet

ASP.NET Core on one page — Program.cs, minimal APIs, controllers and Razor Pages, dependency injection, configuration, validation, EF Core, middleware order, tests, and the traps that show up in interviews.

10 sections 10 tables 16 code snippets

Project & Program.cs

Create and run

dotnet new webapi -n Shop
cd Shop
dotnet run
dotnet test

The host

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

var app = builder.Build();
app.MapControllers();
app.Run();

Which template

CommandWhat you get
dotnet new webapiJSON. Minimal APIs or controllers. This page follows that shape
dotnet new mvcControllers plus Razor views
dotnet new webappRazor Pages. A PageModel and a .cshtml file
dotnet runKestrel. The URL is printed, and launchSettings.json chooses the port
No Startup.csNew apps keep services and the pipeline in Program.cs

This page is ASP.NET Core. System.Web, Global.asax, and Web Forms are the .NET Framework stack.

Minimal APIs

Map a few endpoints

app.MapGet("/books", (BookService books) => books.List());

app.MapGet("/books/{id:int}", (int id, BookService books) =>
{
    var book = books.Find(id);
    return book is null ? Results.NotFound() : Results.Ok(book);
});

app.MapPost("/books", (CreateBook body, BookService books) =>
{
    var created = books.Add(body);
    return Results.Created("/books/" + created.Id, created);
});

How a parameter is bound

ParameterComes from
{id:int}The route. A non-integer is a 404, not a 400
A string or int with no route slotThe query string
A class or recordThe JSON body
A service, such as BookServiceDependency injection, not the request
Results.Created201 plus a Location header

Controllers & Razor

A JSON controller

[ApiController]
[Route("api/books")]
public class BooksController : ControllerBase
{
    [HttpGet("{id:int}")]
    public ActionResult<Book> Get(int id)
    {
        var book = books.Find(id);
        return book is null ? NotFound() : Ok(book);
    }
}

A Razor Page

@page
@model IndexModel

@foreach (var book in Model.Books)
{
    <p>@book.Title</p>
}

Which style

StyleUse it when
Minimal APIA small JSON surface. The handler is a lambda in Program.cs
[ApiController]A larger JSON API. Invalid models become 400 before the action runs
ControllerBaseAn API. Use Controller only when you also call View()
Razor PageHTML. OnGet handles GET. The file starts with @page
[FromBody] / [FromQuery]Force a source when the default guess is wrong

Dependency injection

Register and take it in the constructor

builder.Services.AddScoped<BookService>();

public class BooksController : ControllerBase
{
    private readonly BookService books;

    public BooksController(BookService books)
    {
        this.books = books;
    }
}

Lifetimes

MethodLifetime
AddTransientA new instance every time it is requested
AddScopedOne instance for the HTTP request. The usual choice for a service or DbContext
AddSingletonOne instance for the process
Captive dependencyA singleton must not take a scoped service. Development logs a warning
Constructor injectionThe container calls the constructor. Do not new the service yourself

A DbContext is scoped. Storing it in a singleton, or in a static field, uses it after its request is over.

Configuration

appsettings.json

{
  "Books": { "PageSize": 20 },
  "ConnectionStrings": {
    "Shop": "Data Source=shop.db"
  }
}

Bind a section

builder.Services.Configure<BookOptions>(
    builder.Configuration.GetSection("Books"));

public class BookOptions
{
    public int PageSize { get; set; } = 20;
}

What overrides what

SourceRule
appsettings.jsonThe base file
appsettings.Development.jsonLoaded when ASPNETCORE_ENVIRONMENT is Development, and it wins
Environment variablesOverride both files. Books__PageSize maps to Books:PageSize
IOptions<BookOptions>The value at startup. Does not reload
IOptionsSnapshot<BookOptions>Reread per request. Do not inject it into a singleton

Connection strings and keys stay out of git. For a laptop, dotnet user-secrets stores them outside the project.

Validation

A request class

public class CreateBook
{
    [Required]
    public string Title { get; set; } = "";

    [Range(1, 5000)]
    public int Pages { get; set; }
}

When the checks run

SetupResult
[ApiController]An invalid body never enters the action. The response is 400
[Required]Null or missing. An empty string still fails Required for a string
[Range]A number outside the bounds
ModelState.IsValidCheck it yourself if the controller does not have [ApiController]
A minimal APIDoes not return 400 by itself. Check the model, or add a validation filter

EF Core

Context and set

public class ShopDb : DbContext
{
    public ShopDb(DbContextOptions<ShopDb> options) : base(options) { }
    public DbSet<Book> Books => Set<Book>();
}

builder.Services.AddDbContext<ShopDb>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("Shop")));

Read and insert

var list = await db.Books.AsNoTracking().ToListAsync();

db.Books.Add(new Book { Title = body.Title });
await db.SaveChangesAsync();

Data rules

RuleWhy
dotnet ef migrations add InitWrites a migration. The tool is dotnet-ef, installed separately
dotnet ef database updateApplies migrations. Editing the class does not change the file
AsNoTrackingA read that will not be saved. Skips the change tracker
SaveChangesAsyncNothing is written until this runs
Do not return IQueryableThe query would run later, outside the request, or leak the schema

Middleware order

The usual order

app.UseExceptionHandler(handler =>
{
    handler.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { title = "Server error" });
    });
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Why the order is fixed

CallMust be
UseExceptionHandlerEarly, so it can catch what runs after it
UseHttpsRedirectionBefore the endpoint, so HTTP is redirected first
UseAuthenticationBefore UseAuthorization. Auth reads the user. Authorization decides
UseCorsBefore authentication, or the browser preflight never reaches your login check
MapControllers / MapGetLast. A matched endpoint ends the pipeline

WebApplicationFactory

Hit the real pipeline

public class BookTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient client;

    public BookTests(WebApplicationFactory<Program> factory)
    {
        client = factory.CreateClient();
    }

    [Fact]
    public async Task List_returns_ok()
    {
        var response = await client.GetAsync("/books");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}

Make Program visible

public partial class Program { }

What the factory does

PieceRole
WebApplicationFactory<Program>Boots the app in memory. No fixed port
CreateClient()An HttpClient aimed at that app
public partial class ProgramTop-level statements hide Program. The test project cannot see it otherwise
[Fact]One xUnit test
Replace a servicefactory.WithWebHostBuilder swaps the database for a test double

Interview traps

Traps worth memorising

TrapWhat happensPrefer
Singleton that takes a DbContextThe context outlives the requestScoped service, or a factory you call per operation
async void in a handlerExceptions disappear. The request can finish earlyasync Task
.Result on a taskBlocks a thread and can deadlock a sync contextawait
No [ApiController]An invalid body still enters the actionThe attribute, or check ModelState
Minimal API and [Required]The attribute is ignored unless validation is wired upA controller, or an explicit check
UseAuthorization without UseAuthenticationThe user is never loaded, so policies fail closedAuthentication first
{id} with no :intAny text matches, then the conversion fails later{id:int} when the key is a number
Returning the EF entityNavigation properties and extra columns leak into JSONA response record
IOptions inside a singleton and expecting reloadsIt keeps the first valueIOptionsMonitor for a singleton
Secret in appsettings.jsonThe connection string is in gitUser secrets locally, environment variables in production
new HttpClient() per requestSockets stay openIHttpClientFactory
Test project cannot find ProgramThe generated class is internalpublic partial class Program in the web project

A response of your own

public record BookResponse(int Id, string Title);

Read without tracking

await db.Books.AsNoTracking()
    .Select(b => new BookResponse(b.Id, b.Title))
    .ToListAsync();

How to use this page: dotnet new webapi, map one GET, and run it. Then add a scoped service in the constructor, a [Required] property on the POST body, and a test that uses WebApplicationFactory.