Trang gọi API
Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 18 trên 20.
Trang do chính API cung cấp dùng chung origin, nên các lời gọi fetch không cần CORS. Hai middleware phục vụ các tệp trong thư mục wwwroot của dự án: app.UseDefaultFiles() chuyển yêu cầu đến / thành /index.html, còn app.UseStaticFiles() gửi tệp đó. Phải đặt bước viết lại đường dẫn lên trước.
const response = await fetch('/api/products');
const products = await response.json();
for (const product of products) {
const item = document.createElement('li');
item.textContent = product.name;
list.append(item);
}fetch gửi yêu cầu và trả về một promise chứa phản hồi, còn response.json() đọc phần thân phản hồi dưới dạng JSON. Đường dẫn bắt đầu bằng / sẽ trỏ đến origin của chính trang đó. textContent hiển thị tên dưới dạng văn bản thuần, vì vậy một sản phẩm có tên <script> không thể chạy dưới dạng code.
Thử thách
Trung bìnhCung cấp cho trình theo dõi nhiệm vụ một trang liệt kê các nhiệm vụ. Bạn có một tệp mới, wwwroot/index.html, có tiêu đề và một <ul id="tasks"> trống.
- Trong
Program.cs, sauapp.UseCors("board");, thêmapp.UseDefaultFiles();, rồi thêmapp.UseStaticFiles(); - Trong
wwwroot/index.html, tại vị trí có chú thích, viết mộtasync function loadTasks()để lấy dữ liệu từ/api/tasks, đọc JSON và thêm một<li>cho mỗi nhiệm vụ vào danh sách, với tiêu đề làmtextContent. Gán lớpdonecho mục của nhiệm vụ đã hoàn thành. Kiểu của trang sẽ gạch ngang mục đó. Sau đó gọiloadTasks().
Các bước kiểm tra chạy .NET, không chạy trình duyệt: chúng kiểm tra xem GET / có trả về trang hay không và API mà trang đọc vẫn hoạt động. Bạn kiểm tra danh sách trong cột.
Thử nhé: nhấn Chạy. Cột gửi GET / và hiển thị trang, trang này liệt kê ba nhiệm vụ, trong đó "Book the meeting room" bị gạch ngang. Gửi GET /index.html: trang vẫn như cũ. Gửi POST { "title": "Order new chairs" } đến /api/tasks, rồi gửi lại GET /: có bốn nhiệm vụ.
Tự làm thử
using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddCors(options =>
{
options.AddPolicy("board", policy => policy
.WithOrigins("https://board.example.com")
.WithMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.WithHeaders("Content-Type")
.WithExposedHeaders("X-Total-Count"));
});
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseCors("board");
var tasks = new List<TaskItem>
{
new(1, "Write the project brief", false, 1),
new(2, "Book the meeting room", true, 3),
new(3, "Send the invoice", false),
};
var nextId = 4;
bool TitleTaken(string title, int exceptId) =>
tasks.Any(t => t.Id != exceptId && string.Equals(t.Title, title, StringComparison.OrdinalIgnoreCase));
app.MapGet("/api/tasks", (bool? done, string? search, int? priority, string? sort, HttpResponse response, int page = 1, int pageSize = 10) =>
{
var errors = new Dictionary<string, string[]>();
if (sort is not null && sort != "id" && sort != "title" && sort != "priority")
errors["sort"] = ["Sort by id, title or priority."];
if (priority is < 1 or > 3)
errors["priority"] = ["Priority is 1 to 3."];
if (page < 1)
errors["page"] = ["Page starts at 1."];
if (pageSize < 1 || pageSize > 50)
errors["pageSize"] = ["Page size is 1 to 50."];
if (errors.Count > 0) return Results.ValidationProblem(errors);
IEnumerable<TaskItem> result = tasks;
if (done is not null) result = result.Where(t => t.Done == done);
if (!string.IsNullOrWhiteSpace(search))
result = result.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));
if (priority is not null) result = result.Where(t => t.Priority == priority);
if (sort == "title") result = result.OrderBy(t => t.Title);
if (sort == "priority") result = result.OrderBy(t => t.Priority);
var matching = result.ToList();
response.Headers["X-Total-Count"] = matching.Count.ToString();
return Results.Ok(matching.Skip((page - 1) * pageSize).Take(pageSize));
});
app.MapGet("/api/tasks/{id:int}", (int id) =>
{
var task = tasks.Find(t => t.Id == id);
return task is null ? Results.NotFound() : Results.Ok(task);
});
app.MapPost("/api/tasks", (TaskInput input) =>
{
var errors = Validation.Errors(input);
if (errors is not null) return Results.ValidationProblem(errors);
if (TitleTaken(input.Title, 0))
return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
var task = new TaskItem(nextId++, input.Title, input.Done, input.Priority);
tasks.Add(task);
return Results.Created($"/api/tasks/{task.Id}", task);
});
app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
var errors = Validation.Errors(input);
if (errors is not null) return Results.ValidationProblem(errors);
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
if (TitleTaken(input.Title, id))
return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
tasks[index] = new TaskItem(id, input.Title, input.Done, input.Priority);
return Results.Ok(tasks[index]);
});
app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
var errors = Validation.Errors(patch);
if (errors is not null) return Results.ValidationProblem(errors);
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
if (patch.Title is not null && TitleTaken(patch.Title, id))
return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
var task = tasks[index];
tasks[index] = task with
{
Title = patch.Title ?? task.Title,
Done = patch.Done ?? task.Done,
Priority = patch.Priority ?? task.Priority,
};
return Results.Ok(tasks[index]);
});
app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
var removed = tasks.RemoveAll(t => t.Id == id);
return removed == 0 ? Results.NotFound() : Results.NoContent();
});
app.MapDelete("/api/tasks", (bool? done) =>
{
if (done != true)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["done"] = ["Add ?done=true to delete the done tasks."],
});
}
tasks.RemoveAll(t => t.Done);
return Results.NoContent();
});
app.Run();
record TaskItem(int Id, string Title, bool Done, int Priority = 2);
record TaskInput(
[property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
bool Done,
[property: Range(1, 3)] int Priority = 2);
record TaskPatch(string? Title, bool? Done, [property: Range(1, 3)] int? Priority);
Tất cả bài học trong REST API
1Tài nguyên và động từ
Tài nguyên và URLTạo mới bằng POST4Dự án: Mức độ ưu tiên
Mức độ ưu tiên của tác vụ