Menu
CoddyTech

أول Middleware لك

جزء من قسم واجهات API المصغّرة في رحلة ASP.NET Core على Coddy. الدرس 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.

challenge icon

التحدي

سهل

توضح كل استجابة إصدار API الذي أجاب عنها، في الترويسة X-Api-Version: 1.

  1. في Program.cs، بين var app = builder.Build(); وapp.UseStaticFiles();، أضف برمجية وسيطة باستخدام app.Use(async (context, next) => { ... });.
  2. تعيّن 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();
quiz iconاختبر نفسك

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

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