我尝试过使用 .NET 7 的最小 API,我认为这是 .NET 团队的一件伟大的事情 我唯一关心的是包含许多具有不同逻辑的端点的中型/大型应用程序
那么,如何在不使用实际 Controller 的情况下对 Controller 的逻辑进行分组?
最佳答案
只要我们不想采用 Controller 的方法,在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();
关于c# - 在 .NET 7 中使用具有最少 API 的 MapGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74430528/