Menu
CoddyTech

صفحة HTML ثابتة

جزء من قسم واجهات API المصغّرة في رحلة ASP.NET Core على Coddy. الدرس 12 من 20.

غالبًا ما يرسل تطبيق الويب ملفات لا تتغير أبدًا: صفحات HTML وملفات CSS وصور. يقدّم ASP.NET Core هذه الملفات من مجلد wwwroot في المشروع بمجرد إضافة البرمجيات الوسيطة للملفات الثابتة. البرمجيات الوسيطة هي شيفرة يمر بها كل طلب في طريقه إلى نقاط النهاية؛ وستكتب بعضًا منها في الفصل التالي.

var app = builder.Build();
app.UseStaticFiles();

عند وجود wwwroot/about.html وwwwroot/css/site.css في المشروع، يستجيب GET /about.html وGET /css/site.css بتلك الملفات، مع Content-Type المطابق للامتداد: text/html وtext/css. العنوان هو المسار داخل wwwroot، من دون wwwroot نفسه. أما الطلب الخاص بملف غير موجود فيتابع إلى نقاط النهاية، لذا يظل GET / يصل إلى MapGet("/").

challenge icon

التحدي

سهل

أصبح لدى API صفحة رئيسية. wwwroot/index.html ملف جديد في مشروعك.

  1. في Program.cs، أضف app.UseStaticFiles(); في السطر الذي يلي var app = builder.Build();.
  2. في wwwroot/index.html، أضف <p><a href="/api/recipes">All recipes</a></p> أسفل الفقرة الأولى.

جرّب ذلك: اضغط على «تشغيل». الطلب الأول هو GET /index.html: الحالة 200، وContent-Type: text/html، وتظهر الصفحة مع عنوانها Recipe Box. تعرض علامة التبويب «المصدر» محتوى HTML الخاص بها. انقر على All recipes لإرسال GET /api/recipes. أرسل GET /: وستظل النتيجة Recipe API is running.

جرّب بنفسك

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;
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();

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