ASP.NET - Web API và Minimal API
ASP.NET Core rất mạnh trong việc xây API REST trả về JSON cho ứng dụng React, Vue, Angular hay di động. Bài này làm API quản lý sinh viên theo hai cách: controller và Minimal API, kèm tài liệu OpenAPI.
Bạn sẽ học được
- Hiểu API REST và mã trạng thái HTTP
- Minimal API với MapGet, MapPost
- API Controller
- OpenAPI, CORS
Cơ sở lý thuyết
Web API trong ASP.NET Core cung cấp dữ liệu (thường là JSON) cho SPA, ứng dụng di động, hệ thống khác. Có hai cách xây dựng:
| Tiêu chí | Controller API | Minimal API |
|---|---|---|
| Cấu trúc | Lớp [ApiController] kế thừa ControllerBase | Hàm lambda đăng ký trực tiếp: app.MapGet(...) |
| Phù hợp | API lớn, nhiều filter, quy ước | Dịch vụ nhỏ, microservice, ít mã |
| Hiệu năng | Tốt | Nhỉnh hơn, hỗ trợ biên dịch AOT |
- [ApiController] tự trả lỗi 400 kèm chi tiết theo chuẩn Problem Details (RFC 9457) khi dữ liệu không hợp lệ.
- TypedResults: Ok, Created, NotFound, NoContent, ValidationProblem – trả đúng mã trạng thái HTTP.
- Nhóm route (MapGroup) gom tiền tố, phân quyền, tài liệu cho nhiều endpoint.
- OpenAPI: .NET 9+ tích hợp sẵn sinh đặc tả qua AddOpenApi(); xem bằng Scalar hoặc Swagger UI.
- DTO (đối tượng truyền dữ liệu) tách hình dạng API khỏi entity CSDL.
Minimal API
var api = app.MapGroup("/api/sinhvien");
api.MapGet("/", async (QlsvContext db) => await db.SinhViens.ToListAsync());
api.MapGet("/{id:int}", async (int id, QlsvContext db) =>
await db.SinhViens.FindAsync(id) is { } sv ? Results.Ok(sv) : Results.NotFound());
api.MapPost("/", async (SinhVien sv, QlsvContext db) =>
{
db.Add(sv); await db.SaveChangesAsync();
return Results.Created($"/api/sinhvien/{sv.Id}", sv);
});
api.MapDelete("/{id:int}", async (int id, QlsvContext db) =>
await db.SinhViens.Where(s => s.Id == id).ExecuteDeleteAsync() > 0 ? Results.NoContent() : Results.NotFound());API Controller
[ApiController]
[Route("api/[controller]")]
public class LopController(QlsvContext db) : ControllerBase
{
[HttpGet] public async Task<ActionResult<List<Lop>>> Get() => await db.Lops.ToListAsync();
}OpenAPI và CORS
builder.Services.AddOpenApi();
builder.Services.AddCors(o => o.AddPolicy("fe", p =>
p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod()));
// ...
app.MapOpenApi(); // /openapi/v1.json
app.UseCors("fe");Dùng tệp .http trong VS/VS Code hoặc Postman để thử API.
Ứng dụng thực tế
Bài toán: xây dựng API điểm cho ứng dụng di động của sinh viên bằng Minimal API: nhóm route, phân trang, trả 201 kèm đường dẫn khi tạo mới, đặc tả OpenAPI để nhóm di động tích hợp:
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi(); // /openapi/v1.json
var api = app.MapGroup("/api/sinh-vien").RequireAuthorization();
api.MapGet("/", async (AppDbContext db, int trang = 1, int co = 20) =>
TypedResults.Ok(await db.SinhVien.AsNoTracking().OrderBy(s => s.Ma)
.Skip((trang - 1) * co).Take(co)
.Select(s => new SinhVienDto(s.Ma, s.HoTen, s.DiemTB)).ToListAsync()));
api.MapGet("/{ma}", async Task<Results<Ok<SinhVienDto>, NotFound>> (string ma, AppDbContext db) =>
await db.SinhVien.Where(s => s.Ma == ma).Select(s => new SinhVienDto(s.Ma, s.HoTen, s.DiemTB))
.FirstOrDefaultAsync() is { } sv ? TypedResults.Ok(sv) : TypedResults.NotFound());
api.MapPost("/", async (TaoSinhVienDto dto, AppDbContext db) =>
{
var sv = new SinhVien { Ma = dto.Ma, HoTen = dto.HoTen, KhoaId = dto.KhoaId };
db.SinhVien.Add(sv); await db.SaveChangesAsync();
return TypedResults.Created("/api/sinh-vien/" + sv.Ma, new SinhVienDto(sv.Ma, sv.HoTen, 0));
}).RequireAuthorization(p => p.RequireRole("PhongDaoTao"));
public record SinhVienDto(string Ma, string HoTen, double DiemTB);
public record TaoSinhVienDto(string Ma, string HoTen, int KhoaId);Mẹo hay
Gọi API này từ ứng dụng React (Bài 10) hoặc Vue (Bài 7) để có một hệ thống full-stack hoàn chỉnh.
Thực hành
- Làm API CRUD sinh viên bằng Minimal API.
- Thử bằng tệp .http hoặc Postman.
- Bật CORS và gọi API từ ứng dụng React/Vue.
Tóm tắt bài học
- Minimal API gọn, API Controller cấu trúc rõ.
- Trả đúng mã trạng thái: 200, 201, 204, 404.
- OpenAPI mô tả API, CORS cho phép frontend gọi.
Trang 9 / 11

