什么是最小API?
创建最小API的步骤
1. 创建项目
shell
dotnet new web -o MinimalApiApp
cd MinimalApiApp
2. 修改项目文件
csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", [HttpGet] () => "Hello World!");
app.Run();
3. 添加路由和处理程序
csharp
app.MapGet("/api/todos", () => Results.Ok(new[] { "Todo 1", "Todo 2" }));
app.MapPost("/api/todos", [FromBody] Todo todo => Results.Ok(todo));
4. 使用模型
csharp
public class Todo
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
5. 运行应用
shell
dotnet run
使用依赖注入
csharp
builder.Services.AddSingleton<ITodoService, TodoService>();
csharp
app.MapGet("/api/todos", (ITodoService todoService) =>
{
return Results.Ok(todoService.GetAll());
});
使用Swagger
shell
dotnet add package NSwag.AspNetCore
csharp
if (app.Environment.IsDevelopment())
{
app.UseOpenApi();
app.UseSwaggerUi();
}
示例代码
csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
var builder = WebApplication.CreateBuilder(args);
// Register services
builder.Services.AddSingleton<ITodoService, TodoService>();
var app = builder.Build();
// Define routes
app.MapGet("/", [HttpGet] () => "Hello World!");
app.MapGet("/api/todos", [HttpGet] (ITodoService todoService) =>
{
return Results.Ok(todoService.GetAll());
});
app.MapPost("/api/todos", [HttpPost] ([FromBody] Todo todo, ITodoService todoService) =>
{
todoService.Add(todo);
return Results.Ok(todo);
});
// Run the app
app.Run();
// Model
public class Todo
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
// Service
public interface ITodoService
{
IEnumerable<Todo> GetAll();
void Add(Todo todo);
}
public class TodoService : ITodoService
{
private List<Todo> _todos = new List<Todo>();
public IEnumerable<Todo> GetAll()
{
return _todos;
}
public void Add(Todo todo)
{
_todos.Add(todo);
}
}
结论
往期精品推荐: