c# - 在 .NET 7 中使用具有最少 API 的 MapGroup

标签 c# .net routes minimal-apis .net-7.0

我尝试过使用 .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/

相关文章:

c# - 使用 LINQPad 查询包含嵌套元素的 XML 文件?

ruby - rspec 索引示例有效但不显示示例

C# 以 List 作为参数插入到 SQL 表中

c# - 在没有 AJAX 的情况下使用 Javascript 的服务器端方法

c# - 为什么最后才调用 GC.KeepAlive,而不是最开始?

c# - 为什么 MapHttpAttributeRoutes() 不从属性添加路由?

javascript - 在 React 中实现硬重载

c# - 是否有像 C++ 中那样带有分隔符的 C# 原始字符串?

c# - ViewModel 中的可绑定(bind)字段

c# - 检查表是否存在 : Table doesn't exist while it exists