Skip to main content

ASP.NET Core Cheatsheet

ASP.NET Core 9 views Apr 2026

Program.cs Setup (Minimal)

var builder = WebApplication.CreateBuilder(args);

// Services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(opt =>
    opt.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddMemoryCache();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opt => { /* config */ });

var app = builder.Build();

// Pipeline
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Controllers

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _svc;
    public ProductsController(IProductService svc) => _svc = svc;

    [HttpGet]
    public async Task<IActionResult> GetAll()
        => Ok(await _svc.GetAllAsync());

    [HttpGet("{id:int}")]
    public async Task<IActionResult> Get(int id) {
        var item = await _svc.GetByIdAsync(id);
        return item is null ? NotFound() : Ok(item);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateProductDto dto) {
        var product = await _svc.CreateAsync(dto);
        return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
    }

    [HttpPut("{id:int}")]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateProductDto dto) {
        if (!await _svc.UpdateAsync(id, dto)) return NotFound();
        return NoContent();
    }

    [HttpDelete("{id:int}")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Delete(int id) {
        await _svc.DeleteAsync(id);
        return NoContent();
    }
}

Minimal APIs (ASP.NET Core 6+)

app.MapGet("/products", async (AppDbContext db) =>
    await db.Products.ToListAsync());

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

app.MapPost("/products", async (Product product, AppDbContext db) => {
    db.Products.Add(product);
    await db.SaveChangesAsync();
    return Results.Created($"/products/{product.Id}", product);
});

app.MapDelete("/products/{id}", async (int id, AppDbContext db) => {
    if (await db.Products.FindAsync(id) is not Product p) return Results.NotFound();
    db.Products.Remove(p);
    await db.SaveChangesAsync();
    return Results.NoContent();
}).RequireAuthorization("AdminPolicy");

// Route groups
var api = app.MapGroup("/api/v1").RequireAuthorization();
api.MapGet("/users", GetUsers);

Dependency Injection Lifetimes

LifetimeMethodCreatedUse for
TransientAddTransientEvery injectionLightweight, stateless services
ScopedAddScopedOnce per requestDbContext, unit-of-work
SingletonAddSingletonOnce everCaches, config, thread-safe services

Configuration

// appsettings.json
// { "Smtp": { "Host": "smtp.example.com", "Port": 587 } }

// Bind to class
builder.Services.Configure<SmtpSettings>(
    builder.Configuration.GetSection("Smtp"));

// Inject
public class EmailService {
    private readonly SmtpSettings _smtp;
    public EmailService(IOptions<SmtpSettings> opts) => _smtp = opts.Value;
}

// Read directly
var host = builder.Configuration["Smtp:Host"];
var port = builder.Configuration.GetValue<int>("Smtp:Port");
var conn = builder.Configuration.GetConnectionString("Default");

Middleware

// Inline middleware
app.Use(async (context, next) => {
    context.Response.Headers.Add("X-Request-Id", Guid.NewGuid().ToString());
    await next();
});

// Short-circuit (terminal)
app.Run(async context => await context.Response.WriteAsync("Hello"));

// Class-based middleware
public class TimingMiddleware {
    private readonly RequestDelegate _next;
    public TimingMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext ctx) {
        var sw = Stopwatch.StartNew();
        await _next(ctx);
        sw.Stop();
        ctx.Response.Headers["X-Elapsed-Ms"] = sw.ElapsedMilliseconds.ToString();
    }
}
app.UseMiddleware<TimingMiddleware>();

Action Results (MVC)

return Ok(data);               // 200 + JSON
return Created(uri, data);     // 201
return CreatedAtAction(...);   // 201 + Location header
return NoContent();            // 204
return BadRequest(errors);     // 400
return Unauthorized();         // 401
return Forbid();               // 403
return NotFound();             // 404
return Conflict();             // 409
return StatusCode(500, msg);   // custom

// MVC views
return View(model);
return View("ViewName", model);
return RedirectToAction("Index", "Home");
return Json(data);
return File(bytes, "application/pdf");

Entity Framework Core Quick Reference

// Query
var users = await _db.Users
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .Select(u => new UserDto(u.Id, u.Name))
    .ToListAsync();

// Find by PK (cached in context)
var user = await _db.Users.FindAsync(id);

// Track or no-track
_db.Users.AsNoTracking().Where(...);

// Insert
_db.Users.Add(new User { Name = "Alice" });
await _db.SaveChangesAsync();

// Update
user.Name = "Bob";
await _db.SaveChangesAsync();

// Delete
_db.Users.Remove(user);
await _db.SaveChangesAsync();

// Raw SQL
var count = await _db.Database
    .ExecuteSqlRawAsync("UPDATE Users SET IsActive=1 WHERE Id={0}", id);

Found this helpful? Share it!

Tweet LinkedIn WhatsApp
Translate Page