Kết thúc yêu cầu sớm
Thuộc phần Minimal API trong hành trình ASP.NET Core của Coddy. Bài học 14 trên 20.
Middleware không gọi next() sẽ kết thúc yêu cầu ngay tại đó và tự trả lời yêu cầu: middleware bên dưới nó, tệp tĩnh và các endpoint sẽ không bao giờ chạy.
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/admin"))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Forbidden");
return;
}
await next();
});StartsWithSegments("/admin") trả về true với /admin và /admin/users, nhưng không trả về true với /administrator. Để chuyển client đến một địa chỉ khác, context.Response.Redirect(url, permanent: true) trả về mã 301 Moved Permanently cùng địa chỉ trong header Location, sau đó trình duyệt sẽ gửi yêu cầu đến địa chỉ đó. Nếu không có permanent: true, nó sẽ trả về mã 302 Found, tức là chỉ chuyển hướng tạm thời.
Thử thách
DễAPI trước đây nằm tại /recipes, không có /api. Các liên kết cũ sẽ dẫn đến địa chỉ mới.
- Trong
Program.cs, bên dưới middlewareX-Api-Versionvà bên trênapp.UseStaticFiles();, hãy thêm một middlewareapp.Usekhác. - Khi
context.Request.Path.StartsWithSegments("/recipes"), hãy gọicontext.Response.Redirect("/api" + context.Request.Path + context.Request.QueryString, permanent: true);rồireturnmà không gọinext(). - Nếu không, hãy gọi
await next();.
Thử nhé: nhấn Chạy. Yêu cầu đầu tiên là GET /recipes/2: trạng thái 301, và thẻ Headers hiển thị Location: /api/recipes/2 cùng X-Api-Version: 1. Gửi GET /recipes?category=soup: Location: /api/recipes?category=soup. Gửi GET /api/recipes/2: 200, không chuyển hướng.
Tự làm thử
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
context.Response.Headers["X-Api-Version"] = "1";
await next();
});
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();
Tất cả bài học trong Minimal API
1Các endpoint đầu tiên
Endpoint đầu tiên của bạnTrả về JSON4Middleware và ghi nhật ký
Middleware đầu tiên của bạn2Kết quả và phần thân JSON
OK và không tìm thấy