קבוצות ניתוב
חלק מהיחידה Minimal APIs במסלול ה-ASP.NET Core של Coddy. שיעור 11 מתוך 20.
נקודות הקצה של אותו משאב חולקות את תחילת הנתיבים שלהן. app.MapGroup(prefix) יוצרת קבוצת נתיבים: כל נקודת קצה שממופים בה מקבלת את הקידומת לפני התבנית שלה.
var orders = app.MapGroup("/api/orders");
orders.MapGet("/", () => orderList);
orders.MapGet("/{id:int}", (int id) => orderList.FirstOrDefault(o => o.Id == id));
orders.MapDelete("/{id:int}", (int id) => orderList.RemoveAll(o => o.Id == id));הנתיבים הם /api/orders/, /api/orders/{id:int} ופעולת DELETE על אותה תבנית. GET /api/orders מתאים ל־/api/orders/, מכיוון שקו נטוי בסוף אינו משנה לאיזה נתיב מתאימה הבקשה. כותבים את הקידומת פעם אחת, כך ששינוי שמה משנה שורה אחת, וקבוצה יכולה להחיל הגדרות על כל נקודות הקצה שלה, כגון דרישה להתחברות. כתיבת הקידומת שוב בתוך הקבוצה מכפילה אותה: /api/orders/api/orders/{id:int}.
אתגר
קלהלומדים יכולים לשמור מתכונים מועדפים. שלושת נקודות הקצה של המועדפים חולקות קבוצה אחת.
- ב־
Program.cs, מתחת ל־nextId, הוסיפוvar favoriteIds = new List<int>();. - מעל
app.Run(), צרו את הקבוצה:var favorites = app.MapGroup("/api/favorites");. - בקבוצה, מפו GET ל־
"/": הוא מחזיר את המתכונים שה־Idשלהם נמצא ב־favoriteIds, לפי הסדר שלrecipes. - מפו POST ל־
"/{id:int}": כשאין מתכון עם המזהה הזה, החזירוResults.NotFound(new { error = $"Recipe {id} not found" }). אחרת, הוסיפו את המזהה אלא אםfavoriteIdsכבר מכיל אותו, והחזירוResults.NoContent(). - מפו DELETE ל־
"/{id:int}": הסירו את המזהה מ־favoriteIdsוהחזירוResults.NoContent().
נסו זאת: לחצו על „הרצה”: GET /api/favorites מחזיר []. שלחו POST /api/favorites/2 עם גוף ריק: סטטוס 204. שלחו GET /api/favorites: רשימה עם המתכון Pancakes. POST /api/favorites/99 מחזיר 404, ו־DELETE /api/favorites/2 מרוקן שוב את הרשימה.
נסו בעצמכם
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
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;
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();
});
app.Run();
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.