排序
本课属于 Coddy ASP.NET Core 学习旅程的“REST API”单元。第 12 课,共 20 课。
sort 参数允许客户端选择排序顺序:GET /api/products?sort=price。只接受你支持的排序方式,其他情况都返回 400。这样,像 sort=prise 这样的拼写错误就会被报告,而不是被忽略。
var errors = new Dictionary<string, string[]>();
if (sort is not null && sort != "name" && sort != "price")
errors["sort"] = ["Sort by name or price."];
if (errors.Count > 0) return Results.ValidationProblem(errors);
if (sort == "price") result = result.OrderBy(p => p.Price);OrderBy 会返回一个新的排序序列,并保持原列表不变。products.Sort(...) 会直接重新排列存储的列表,因此之后的每次响应也都会按新的顺序返回。把错误收集到同一个字典中,可以一次性告知请求中的多个错误。
挑战
简单让客户端按标题排序任务。
- 为
GET /api/taskslambda 添加第三个参数string? sort。 - 在 lambda 开始处,将错误收集到一个字典中。当
sort既不是null,也不是id或title时,在sort下添加Sort by id or title.,并在字典中有任何错误时返回Results.ValidationProblem(errors)。 - 在筛选之后,如果
sort是title,则用OrderBy按标题对结果排序。不指定sort或指定sort=id时,任务仍按 id 顺序排列。
GET /api/tasks?sort=title 返回任务 2、3 和 1:Book、Send、Write。
试试看:按“运行”,然后发送 GET /api/tasks?sort=title:顺序如上。发送 GET /api/tasks:恢复为按 id 排序。发送 GET /api/tasks?sort=size:返回 400,内容为 "errors": { "sort": ["Sort by id or title."] }。发送 GET /api/tasks?done=false&sort=title:返回任务 3 和 1。
亲手试试
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) =>
{
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));
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);