基于 Minimal APIs 的Web API
Minimal APIs 是ASP.NET Core中快速构建 REST API 的方式,可以用最少的代码构建全功能的REST API。比如下面三行代码:
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
可以实现在请求网站根目录结点的时候,返回"Hello World!"。
这种方式的Web API可以用于构建微服务,极简功能的网站。
映射 HTTP 请求
下面代码,将几个 HTTP 请求的 url映射到 Lambda 函数中,分别是:
- HTTP GET,/todoitems ,获取所有todoitems
- HTTP GET,/todoitems/complete,获取所有完成的todoitems
- HTTP GET,/todoitems/{id},获取某个 id 的todoitem
- HTTP Post,/todoitems,添加一个todoitem
- HTTP PUT,/todoitems/{id},修改某个 id 的todoitem
- HTTP DELETE,/todoitems/{id},删除某个 id 的todoitem
using Microsoft.EntityFrameworkCore;var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();app.MapGet("/todoitems", async (TodoDb db) =>await db.Todos.ToListAsync());app.MapGet("/todoitems/complete", async (TodoDb db) =>await db.Todos.Where(t => t.IsComplete).ToListAsync());app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>await db.Todos.FindAsync(id)is Todo todo? Results.Ok(todo): Results.NotFound());app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{db.Todos.Add(todo);await db.SaveChangesAsync();return Results.Created($"/todoitems/{todo.Id}", todo);
});app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{var todo = await db.Todos.FindAsync(id);if (todo is null) return Results.NotFound();todo.Name = inputTodo.Name;todo.IsComplete = inputTodo.IsComplete;await db.SaveChangesAsync();return Results.NoContent();
});app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{if (await db.Todos.FindAsync(id) is Todo todo){db.Todos.Remove(todo);await db.SaveChangesAsync();return Results.NoContent();}return Results.NotFound();
});app.Run();