After this lesson, you will be able to: Build a REST API in ASP.NET Core with controllers or minimal APIs, routing, middleware, and dependency injection.
ASP.NET Core is the .NET web framework. Fastest mainstream web framework (per TechEmpower benchmarks). Built-in DI, middleware pipeline, OpenAPI support. The bread and butter of C# backend jobs.
Lightweight; great for microservices.
// Create: dotnet new webapi -minimal -o myapi && cd myapi && dotnet runvar builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<IUserStore, InMemoryUserStore>();var app = builder.Build();// Routesapp.MapGet("/", () => "Hello!");app.MapGet("/users/{id:int}", async (int id, IUserStore store) => {var user = await store.FindByIdAsync(id);return user is null ? Results.NotFound() : Results.Ok(user);});app.MapPost("/users", async (User user, IUserStore store) => {await store.SaveAsync(user);return Results.Created($"/users/{user.Id}", user);});app.Run();// User typepublic record User(int Id, string Name, string Email);
Preferred for big APIs with many routes.
// Controllers/UsersController.cs[ApiController][Route("users")]public class UsersController : ControllerBase {private readonly IUserStore _store;public UsersController(IUserStore store) {_store = store;}[HttpGet("{id:int}")]public async Task<ActionResult<User>> GetById(int id) {var user = await _store.FindByIdAsync(id);return user is null ? NotFound() : Ok(user);}[HttpPost]public async Task<ActionResult<User>> Create(User user) {await _store.SaveAsync(user);return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);}}// Program.csvar builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();builder.Services.AddSingleton<IUserStore, InMemoryUserStore>();var app = builder.Build();app.MapControllers();app.Run();
Request-response chain. Order matters.
var app = builder.Build();// Exception handler, outermostapp.UseExceptionHandler("/error");// HTTPS redirectapp.UseHttpsRedirection();// CORSapp.UseCors("AllowAll");// Authapp.UseAuthentication();app.UseAuthorization();// Custom middleware (inline)app.Use(async (context, next) => {Console.WriteLine($"{context.Request.Method} {context.Request.Path}");await next.Invoke();Console.WriteLine($" → {context.Response.StatusCode}");});// Routes, innermostapp.MapControllers();app.Run();
Wrong DI lifetime (Scoped vs Singleton vs Transient, read carefully). Skipping `AddCors` then puzzling over CORS errors. Forgetting `app.MapControllers()`, routes won't match. Putting business logic in controllers (extract to services).
Sign in and purchase access to unlock this lesson.