ASP.NET Core 有两种创建 RESTful Web API 的方式:
- 基于 Controller,使用完整的基于ControllerBase的基类定义接口endpoints。
- 基于 Minimal APIs,使用Lambda表达式定义接口 endpoints。
基于 Controller 的 Web API 可以使用构造函数注入,或者属性注入,遵循面向对象模式。
基于 Minimal APIs 的 Web API 通过 service provider 使用注入。
基于Controller 的 Web API 例子:
namespace APIWithControllers;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
}
}
using Microsoft.AspNetCore.Mvc;
namespace APIWithControllers