ASP.NET Core dùng để xây web app và Web API trên .NET.
Minimal API gọn cho API nhỏ; Controller phù hợp khi project lớn và cần tổ chức rõ.
var builder = WebApplication . CreateBuilder (args);
builder . Services . AddEndpointsApiExplorer ();
builder . Services . AddSwaggerGen ();
var app = builder . Build ();
app . MapGet ( " / " , () => " Hello API " );
var todos = new List<TodoDto>();
app . MapGet ( " /todos " , () => todos);
app . MapGet ( " /todos/{id:int} " , ( int id) =>
todos . FirstOrDefault (t => t . Id == id) is { } todo
app . MapPost ( " /todos " , (TodoDto todo) =>
return Results . Created ( $" /todos/ { todo . Id } " , todo);
app . MapPut ( " /todos/{id:int} " , ( int id, TodoDto input) =>
int index = todos . FindIndex (t => t . Id == id);
if (index < 0 ) return Results . NotFound ();
todos [index] = input with { Id = id };
return Results . NoContent ();
app . MapDelete ( " /todos/{id:int} " , ( int id) =>
todos . RemoveAll (t => t . Id == id);
return Results . NoContent ();
public record TodoDto ( int Id, string Title, bool Done);
Khái niệm Ghi nhớ Minimal API Khai báo endpoint trực tiếp bằng MapGet, MapPost Controller Class chứa action API Routing Map URL tới handler Middleware Code chạy trong HTTP pipeline DI Inject service qua constructor/parameter DTO Object truyền dữ liệu request/response Status Code 200, 201, 400, 404, 500Swagger UI test API
Method Dùng để Ví dụ route GETLấy dữ liệu GET /productsPOSTTạo mới POST /productsPUTCập nhật toàn bộ PUT /products/1PATCHCập nhật một phần PATCH /products/1DELETEXóa DELETE /products/1
Code Ý nghĩa Helper 200OK Results.Ok(data)201Created Results.Created(url, data)204No Content Results.NoContent()400Bad Request Results.BadRequest(error)401Unauthorized Results.Unauthorized()403Forbidden Results.Forbid()404Not Found Results.NotFound()500Server Error Không trả chi tiết lỗi nội bộ
builder . Services . AddScoped <IProductService, ProductService>();
app . MapGet ( " /products " , async (IProductService service) =>
Results . Ok ( await service . GetAllAsync ()));
Lifetime Khi dùng SingletonMột instance cho toàn app ScopedMột instance mỗi request web TransientTạo mới mỗi lần inject
app . UseExceptionHandler ( " /error " );
app . UseHttpsRedirection ();
Thứ tự middleware quan trọng vì request đi qua pipeline theo thứ tự khai báo.
[Route( " api/[controller] " )]
public class ProductsController : ControllerBase
public IActionResult GetAll () => Ok ( new [] { " Mouse " , " Keyboard " });
public record CreateProductRequest ( string Name, decimal Price);
app . MapPost ( " /products " , (CreateProductRequest request) =>
if ( string . IsNullOrWhiteSpace ( request . Name ) || request . Price < 0 )
return Results . BadRequest ( " Invalid product " );
return Results . Created ( " /products/1 " , request);
Quên gọi app.MapControllers() khi dùng Controller.
Trả entity database trực tiếp thay vì DTO.
Thiếu status code rõ ràng cho lỗi validation/not found.
Đăng ký service sai lifetime, ví dụ inject DbContext vào singleton.
Đặt middleware authentication/authorization sai thứ tự.
Dùng Minimal API lớn nhưng không chia route group/service.
ASP.NET Core, Minimal API, Controller, routing, route group, middleware, dependency injection, DI, service lifetime, DTO, validation, status code, Swagger, OpenAPI, Web API