Menu
CoddyTech

调用 API 的页面

本课属于 Coddy ASP.NET Core 学习旅程的“REST API”单元。第 18 课,共 20 课。

由 API 本身提供的页面与 API 共享同一来源,因此它的 fetch 调用不需要 CORS。两个中间件负责提供项目的 wwwroot 文件夹中的文件:app.UseDefaultFiles() 会将对 / 的请求转换为 /index.html,而 app.UseStaticFiles() 会发送文件。重写必须先执行。

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 会发送请求,并返回一个以响应为结果的 Promise;response.json() 会将响应正文读取为 JSON。以 / 开头的路径会指向页面自身的来源。textContent 会将名称显示为纯文本,因此名为 <script> 的产品不会作为代码运行。

challenge icon

挑战

中等

为任务跟踪器添加一个列出任务的页面。你有一个新文件 wwwroot/index.html,其中包含一个标题和一个空的 <ul id="tasks">。

  1. 在 Program.cs 中,app.UseCors("board"); 后面添加 app.UseDefaultFiles();,然后添加 app.UseStaticFiles();
  2. 在 wwwroot/index.html 中,在注释所在的位置,编写一个 async function loadTasks(),用于获取 /api/tasks、读取 JSON,并为列表中的每个任务添加一个 <li>,并将任务标题设为其 textContent。给已完成任务的条目添加 done 类,页面样式会为其标题添加删除线。然后调用 loadTasks()。

检查会运行 .NET,而不是浏览器:它们会检查 GET / 是否返回页面,以及页面读取的 API 是否仍能正常工作。你可以在列中检查列表本身。

试试看:按“运行”。该列会发送 GET / 并显示页面,其中列出了三个任务,并为 "Book the meeting room" 添加了删除线。发送 GET /index.html:会显示同一个页面。向 /api/tasks 发送 POST { "title": "Order new chairs" },然后再次发送 GET /:现在会有四个任务。

亲手试试

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);

REST API中的所有课