在.net 7中使用MapGroup和最少的api



我尝试过使用。net 7的最小API,我认为这是。net团队的一件伟大的事情我唯一关心的是中型/大型应用程序,它们包含许多具有不同逻辑的端点

那么,如何在不使用实际控制器的情况下对控制器的逻辑进行分组?

只要我们不想使用控制器的方法,在Dotnet7中我们可以使用MapGroup(),这是一个静态类,它创建一个RouteGroupBuilder来定义所有端点

模型
internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

对端点进行分组的静态类

public static class WeatherForecastGroup
{
public static void MapWeatherForecast(this IEndpointRouteBuilder routeBuilder)
{
routeBuilder.MapGet("/weatherforecast", GetAllWeatherForecast).WithName("GetWeatherForecast").WithOpenApi();
}
private static IResult GetAllWeatherForecast()
{
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return Results.Ok(forecast);
}
}

我们的program。cs文件就像

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapWeatherForecast();
app.Run();

最新更新