Minimal APIs là một tính năng được giới thiệu trong .NET 6, cho phép nhà phát triển tạo các API gọn gàng hơn, dễ đọc hơn, và nhanh chóng bắt đầu hơn so với các cách tiếp cận ASP.NET Core Web API truyền thống. Hãy cùng tìm hiểu Minimal APIs là gì và tại sao nó lại đáng chú ý.
Ưu điểm của Minimal APIs
- Xây dựng các API nhỏ hoặc đơn giản.
- Đối với các ứng dụng không có nhiều cấu trúc phức tạp.
- Khi bạn cần prototyping nhanh chóng
- API đơn giản, không yêu cầu nhiều cấu hình.
- Xây dựng nhanh chóng mà không cần nhiều tài nguyên.
- Prototype hoặc đáp ứng các nhu cầu testing.
Tạo Project Minimal APIs bằng Visual Studio
Mở Visual Studio: Chọn phiên bản Visual Studio hỗ trợ .NET 8 trở lên (ví dụ: Visual Studio 2022).
Tạo Project mới:
- Chọn File → New → Project.
- Trong cửa sổ Create a new project, tìm kiếm ASP.NET Core Empty.
- Nhấn Next.
Cấu hình dự án:
- Nhập tên dự án và chọn vị trí lưu.
- Nhấn Next.
Chọn Framework:
- Ở bước Additional information, chọn .NET 8.0 (Long-term support) hoặc phiên bản cao hơn.
- Nhấn Create.
Dưới đây là 1 đoạn code API đơn giản
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, World!");
app.Run();
Chỉ với vài dòng code, bạn đã tạo được một API nhận GET request tại endpoint /hello và trả về chuỗi "Hello, World!".
Vấn đề
Một trong những mối lo ngại thường gặp nhất khi sử dụng Minimal APIs là khi ứng dụng của bạn trở nên lớn hơn, file Program.cs sẽ trở nên rất khó quản lý
using MinimalApiSample.Models;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, World!");
var todoItems = new List<TodoItem>()
{
new TodoItem { Id = 1, Name = "Learn .NET 9 Minimal APIs", IsComplete = true },
new TodoItem { Id = 2, Name = "Build a Simple To-Do API", IsComplete = false }
};
app.MapGet("/", () => "Hello World!");
// Define the API endpoints using Minimal API style
app.MapGet("/todos", () => Results.Ok(todoItems));
app.MapGet("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
return todo is not null ? Results.Ok(todo) : Results.NotFound();
});
app.MapPost("/todos", (TodoItem newTodo) =>
{
newTodo.Id = todoItems.Max(t => t.Id) + 1;
todoItems.Add(newTodo);
return Results.Created($"/todos/{newTodo.Id}", newTodo);
});
app.MapPut("/todos/{id:int}", (int id, TodoItem updatedTodo) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todo.Name = updatedTodo.Name;
todo.IsComplete = updatedTodo.IsComplete;
return Results.Ok(todo);
});
app.MapDelete("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todoItems.Remove(todo);
return Results.NoContent();
});
app.Run();
Khai báo TodoItem ở MinimalApiSample/Models
public class TodoItem
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
Cách 1
Đưa các endpoint mapping vào các folder Features
Tạo file TodoEndpointusing MinimalApiSample.Models;
namespace MinimalApiSample.Features.Todos;
public static class TodoEndpoint
{
static List<TodoItem> todoItems = new List<TodoItem>()
{
new TodoItem { Id = 1, Name = "Learn .NET 9 Minimal APIs", IsComplete = true },
new TodoItem { Id = 2, Name = "Build a Simple To-Do API", IsComplete = false }
};
public static void AddTodoEndpoint(this WebApplication app)
{
// Define the API endpoints using Minimal API style
app.MapGet("/todos", () => Results.Ok(todoItems));
app.MapGet("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
return todo is not null ? Results.Ok(todo) : Results.NotFound();
});
app.MapPost("/todos", (TodoItem newTodo) =>
{
newTodo.Id = todoItems.Max(t => t.Id) + 1;
todoItems.Add(newTodo);
return Results.Created($"/todos/{newTodo.Id}", newTodo);
});
app.MapPut("/todos/{id:int}", (int id, TodoItem updatedTodo) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todo.Name = updatedTodo.Name;
todo.IsComplete = updatedTodo.IsComplete;
return Results.Ok(todo);
});
app.MapDelete("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todoItems.Remove(todo);
return Results.NoContent();
});
}
}
Ở file program.cs, bạn xóa đoạn mapping đi, thay thế bằng dòng code sau:
app.AddTodoEndpoint();
Toàn bộ đoạn code trong Program.cs như sau:
using MinimalApiSample.Features.Posts;
using MinimalApiSample.Features.Todos;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.AddTodoEndpoint();
app.Run();
public record Post(string Name);
public record Posted(int id, string Name, string body);
Cách 2: Endpoint
Trong Minimal API, Endpoint là cách để định nghĩa các chức năng API bằng cách ánh xạ các phương thức HTTP (GET, POST, PUT, DELETE, ...) vào các đường dẫn cụ thể.
Ví dụ:
Endpoint /todos với phương thức HTTP GET dùng để trả về danh sách tất cả các công việc.
Endpoint /todos/{id} với phương thức HTTP GET dùng để trả về một công việc cụ thể dựa trên id.
public interface IEndpoint
{
void MapEndpoint(IEndpointRouteBuilder app);
}
Cập nhật lại class TodoEndpoint
using MinimalApiSample.Models;
namespace MinimalApiSample.Features.Todos;
public class TodoEndpoint : IEndpoint
{
static List<TodoItem> todoItems = new List<TodoItem>()
{
new TodoItem { Id = 1, Name = "Learn .NET 9 Minimal APIs", IsComplete = true },
new TodoItem { Id = 2, Name = "Build a Simple To-Do API", IsComplete = false }
};
public void MapEndpoint(IEndpointRouteBuilder app)
{
// Define the API endpoints using Minimal API style
app.MapGet("/todos", () => Results.Ok(todoItems));
app.MapGet("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
return todo is not null ? Results.Ok(todo) : Results.NotFound();
});
app.MapPost("/todos", (TodoItem newTodo) =>
{
newTodo.Id = todoItems.Max(t => t.Id) + 1;
todoItems.Add(newTodo);
return Results.Created($"/todos/{newTodo.Id}", newTodo);
});
app.MapPut("/todos/{id:int}", (int id, TodoItem updatedTodo) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todo.Name = updatedTodo.Name;
todo.IsComplete = updatedTodo.IsComplete;
return Results.Ok(todo);
});
app.MapDelete("/todos/{id:int}", (int id) =>
{
var todo = todoItems.FirstOrDefault(t => t.Id == id);
if (todo is null) return Results.NotFound();
todoItems.Remove(todo);
return Results.NoContent();
});
}
}
Cập nhật lại đoạn code đăng ký Endpoint trong program.cs:
// Register individual endpoints
//app.AddTodosEndpoint();
var todoEndpoint = new TodoEndpoint();
todoEndpoint.MapEndpoint(app);
Nhận xét
Đăng nhận xét