你的第一个中间件
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 13 课,共 20 课。
中间件是每个请求都会经过的代码,顺序取决于应用添加中间件的先后,并且在端点响应之前运行。app.Use可以添加一个中间件。它会获取保存请求和响应的HttpContext,以及用于运行管道中剩余部分的next。
app.Use(async (context, next) =>
{
context.Response.Headers["Cache-Control"] = "no-store";
await next();
});await next()之前的代码会在请求进入时运行,之后的代码会在请求返回时运行。响应会先发送标头,再发送正文,因此要在调用next()之前设置标头:端点写入正文后,标头就无法再更改。中间件只能看到到达它的请求,而app.UseStaticFiles()会自行响应文件请求,因此添加在它之后的中间件永远看不到/index.html。
挑战
简单每个响应都会在标头 X-Api-Version: 1 中说明响应它的 API 版本。
- 在
Program.cs中的var app = builder.Build();和app.UseStaticFiles();之间,添加一个中间件:app.Use(async (context, next) => { ... });。 - 它会设置
context.Response.Headers["X-Api-Version"] = "1";,然后调用await next();。
试试看:按下“运行”。GET /api/recipes 的响应与之前相同,其“Headers”选项卡会显示 X-Api-Version: 1。发送 GET /index.html:响应中也有这个标头。发送 GET /nothing:状态码为 404,响应中也有这个标头。
亲手试试
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
var recipes = new List<Recipe>
{
new(1, "Tomato Soup", "soup", 25),
new(2, "Pancakes", "breakfast", 15),
new(3, "Lentil Soup", "soup", 40),
};
var nextId = 4;
var favoriteIds = new List<int>();
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id) =>
{
var recipe = recipes.FirstOrDefault(r => r.Id == id);
if (recipe is null)
return Results.NotFound(new { error = $"Recipe {id} not found" });
return Results.Ok(recipe);
});
app.MapPost("/api/recipes", (NewRecipe input) =>
{
if (string.IsNullOrWhiteSpace(input.Name))
return Results.BadRequest(new { error = "Name is required" });
if (input.Minutes <= 0)
return Results.BadRequest(new { error = "Minutes must be more than 0" });
var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
recipes.Add(recipe);
return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});
app.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
var index = recipes.FindIndex(r => r.Id == id);
if (index == -1)
return Results.NotFound(new { error = $"Recipe {id} not found" });
var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
recipes[index] = recipe;
return Results.Ok(recipe);
});
app.MapDelete("/api/recipes/{id:int}", Results<NoContent, NotFound> (int id) =>
{
var removed = recipes.RemoveAll(r => r.Id == id);
return removed > 0 ? TypedResults.NoContent() : TypedResults.NotFound();
});
var favorites = app.MapGroup("/api/favorites");
favorites.MapGet("/", () => recipes.Where(r => favoriteIds.Contains(r.Id)));
favorites.MapPost("/{id:int}", (int id) =>
{
if (!recipes.Any(r => r.Id == id))
return Results.NotFound(new { error = $"Recipe {id} not found" });
if (!favoriteIds.Contains(id))
favoriteIds.Add(id);
return Results.NoContent();
});
favorites.MapDelete("/{id:int}", (int id) =>
{
favoriteIds.Remove(id);
return Results.NoContent();
});
app.Run();
这节课包含一个小测验。开始学习即可作答,并记录你的进度。