静态 HTML 页面
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 12 课,共 20 课。
Web 应用通常会发送不会变化的文件: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("/")。
挑战
简单为这个 API 添加一个主页。wwwroot/index.html 是项目中新建的文件。
- 在
Program.cs中的var app = builder.Build();下一行,添加app.UseStaticFiles();。 - 在
wwwroot/index.html中的第一个段落下方,添加<p><a href="/api/recipes">All recipes</a></p>。
试试看:点击“运行”。第一个请求是 GET /index.html:状态码为 200,Content-Type: text/html,页面会显示标题 Recipe Box。“Source”选项卡会显示 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();