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 例子:
csharp
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();
}
}
csharp
using Microsoft.AspNetCore.Mvc;
namespace APIWithControllers.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
基于 Minimal APIs 的 Web API 例子:
csharp
namespace MinimalAPI;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", (HttpContext httpContext) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
});
app.Run();
}
}
同样的功能可以用两种方式实现。
但是有些功能Minimal APIs 的 Web API没有,包括:
- 没有原生支持 model binding
- 没有原生支持 validation
- 不支持 application parts 或者 application model
- 没有原生支持 view 渲染
- 不支持 JsonPatch
- 不支持 OData