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 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(); This page is ASP.NET Core. System.Web, Global.asax, and Web Forms are the .NET Framework stack. 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);
}); 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>
} 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;
}
} A DbContext is scoped. Storing it in a singleton, or in a static field, uses it after its request is over. 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;
} Connection strings and keys stay out of git. For a laptop, dotnet user-secrets stores them outside the project. A request class public class CreateBook
{
[Required]
public string Title { get; set; } = "";
[Range(1, 5000)]
public int Pages { get; set; }
} 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(); 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(); 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 { } 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. |