Menu
CoddyTech

任务优先级

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

这一章是一个项目:你会用学到的知识为 API 添加一项功能。有些任务很紧急,因此每个任务都有一个优先级:1 表示高,2 表示普通,3 表示低。

record Seat(int Row, [property: Range(1, 40)] int Number = 1);

[Range(1, 40)]会拒绝超出 1 到 40 范围的数字,并显示消息 The field Number must be between 1 and 40.位置记录中的默认值(= 1)就是 JSON 请求体省略该字段时使用的值。对于可空属性,Range会允许 null 通过,这适用于 PATCH。

challenge icon

挑战

中等

为每个任务设置优先级,1(高)到 3(低)。保留你构建的所有内容:每个端点都继续像之前一样正常工作。

  1. 将 int Priority = 2 添加为 TaskItem 的最后一个属性。将任务 1 的优先级设为 1,任务 2 的优先级设为 3;任务 3 保持默认值 2。
  2. 将 [property: Range(1, 3)] int Priority = 2 添加为 TaskInput 的最后一个属性,并在 POST 和 PUT 中将 input.Priority 传给新的 TaskItem。
  3. 将 [property: Range(1, 3)] int? Priority 添加到 TaskPatch。在 PATCH 开始时,使用 Validation.Errors(patch) 检查补丁;如果发现错误,就返回 Results.ValidationProblem。像其他字段一样,在 with 中复制优先级。

现在,每个任务都带有优先级:{ "id": 1, "title": "Write the project brief", "done": false, "priority": 1 }。优先级为 5 时,返回 400,并附带 "errors": { "priority": ["The field Priority must be between 1 and 3."] }。

试试看:按“运行”:列表中的每个任务都有优先级。发送 POST { "title": "Order new chairs" }:优先级为 2。发送 POST { "title": "Fix the printer", "priority": 5 }:返回 400。向 /api/tasks/3 发送 PATCH,并附带 { "priority": 1 }:任务 3 会变为紧急任务,同时保留原有标题。

亲手试试

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    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, 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")
        errors["sort"] = ["Sort by id or title."];
    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 (sort == "title") result = result.OrderBy(t => t.Title);

    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);
    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);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    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,
    };
    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.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);

REST API中的所有课