Menu
CoddyTech

Statyczna strona HTML

Część sekcji Minimal APIs ścieżki ASP.NET Core w Coddy. Lekcja 12 z 20.

Aplikacja internetowa często wysyła pliki, które nigdy się nie zmieniają: strony HTML, pliki CSS, obrazy. ASP.NET Core udostępnia je z folderu wwwroot projektu po dodaniu oprogramowania pośredniczącego do obsługi plików statycznych. Oprogramowanie pośredniczące to kod, przez który przechodzi każde żądanie w drodze do punktów końcowych; w następnym rozdziale napiszemy taki kod.

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

Gdy w projekcie znajdują się pliki wwwroot/about.html i wwwroot/css/site.css, żądania GET /about.html i GET /css/site.css zwracają te pliki z nagłówkiem Content-Type odpowiadającym rozszerzeniu: text/html, text/css. Adres to ścieżka wewnątrz wwwroot, bez samego wwwroot. Żądanie dotyczące pliku, który nie istnieje, przechodzi dalej do punktów końcowych, więc GET / nadal trafia do MapGet("/").

challenge icon

Wyzwanie

Łatwy

API otrzymuje stronę główną. wwwroot/index.html to nowy plik w Twoim projekcie.

  1. W Program.cs, w wierszu po var app = builder.Build();, dodaj app.UseStaticFiles();.
  2. W wwwroot/index.html, poniżej pierwszego akapitu, dodaj <p><a href="/api/recipes">All recipes</a></p>.

Wypróbuj: naciśnij Uruchom. Pierwsze żądanie to GET /index.html: status 200, Content-Type: text/html, a strona wyświetla się z nagłówkiem Recipe Box. Karta Źródło pokazuje kod HTML. Kliknij All recipes, aby wysłać GET /api/recipes. Wyślij GET /: nadal Recipe API is running.

Spróbuj swoich sił

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

Wszystkie lekcje w sekcji Minimal APIs