Menu
CoddyTech

مجموعات المسارات

جزء من قسم واجهات API المصغّرة في رحلة 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}.

challenge icon

التحدي

سهل

يمكن للمتعلمين الاحتفاظ بالوصفات المفضلة. تشترك نقاط النهاية الثلاث للمفضلة في مجموعة واحدة.

  1. في Program.cs، أضف var favoriteIds = new List<int>(); أسفل nextId.
  2. أنشئ المجموعة فوق app.Run(): var favorites = app.MapGroup("/api/favorites");.
  3. على المجموعة، اربط GET مع "/": يعيد ذلك الوصفات التي يكون Id فيها ضمن favoriteIds، وبترتيب recipes.
  4. اربط POST مع "/{id:int}": عندما لا توجد وصفة بهذا المعرّف، أعد Results.NotFound(new { error = $"Recipe {id} not found" }). وإلا فأضف المعرّف ما لم يكن favoriteIds يحتوي عليه بالفعل، ثم أعد Results.NoContent().
  5. اربط 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();
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس واجهات API المصغّرة