在.NET 7中使用具有最少API的MapGroup [duplicate]

fumotvh3  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(147)

此问题在此处已有答案

Minimal API in .NET 6 using multiple files(5个答案)
4天前关闭。
我尝试过使用.NET 7的最小API,我认为.NET团队的做法很棒。我唯一担心的是包含许多具有不同逻辑的端点的大中型应用程序
那么,如何在不使用实际控制器的情况下对控制器的逻辑进行分组呢?

uklbhaso

uklbhaso1#

只要我们不想使用控制器的方法,在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();

相关问题