Menu
CoddyTech

搜索

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

搜索是查询字符串中的另一种筛选条件。在库的 API 中,GET /api/books?search=potter会返回标题中包含该文本的图书。筛选条件可以叠加:每个条件都会进一步缩小前一个条件筛选后的范围。

if (!string.IsNullOrWhiteSpace(search))
    result = result.Where(b =>
        b.Title.Contains(search, StringComparison.OrdinalIgnoreCase));

Contains默认会进行精确比较,所以搜索potter时会找不到Potter。StringComparison.OrdinalIgnoreCase会忽略大小写。如果搜索内容为null或为空,就跳过筛选:?search=会发送一个空字符串,而清空搜索框的客户端希望重新获取整个列表。

challenge icon

挑战

简单

让客户端通过标题中的某个词查找任务。

  1. 为 GET /api/tasks lambda 添加第二个参数 string? search。
  2. 在 done 筛选后,如果 search 不是 null 或空白字符,就保留标题包含该内容的任务,不区分大小写。
  3. 保留 done 筛选:这两个筛选会一起生效。

GET /api/tasks?search=ROOM 会返回任务 2,Book the meeting room。GET /api/tasks?search=the&done=false 会返回任务 1 和 3:每个标题都包含 "the",而这两个任务尚未完成。

试试看:按“运行”,然后发送 GET /api/tasks?search=ROOM:会得到任务 2。发送 GET /api/tasks?search=in:会得到任务 2 和 3,因为它们的标题中分别有 meeting 和 invoice。发送 GET /api/tasks?search=:会得到全部三个任务。

亲手试试

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) =>
{
    IEnumerable<TaskItem> result = tasks;
    if (done is not null) result = result.Where(t => t.Done == done);
    return Results.Ok(result);
});

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中的所有课