2

I've tried to use the .NET 7's minimal API, I think it's a great thing from the .NET team my only concern was about the medium / Large applications that contain a lot of end-points with different logic

So, how to group my controller's logic without using actual controllers?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
esamaldin elzain
  • 320
  • 1
  • 4
  • 16

1 Answers1

2

As long as we don't want to go with the controller's approach, In Dotnet7 we can use MapGroup(), which is a static class that Creates a RouteGroupBuilder for defining all endpoints

Model

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

Static class for grouping our endpoints

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);
    }
}

And our Program.cs file will be like

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();
esamaldin elzain
  • 320
  • 1
  • 4
  • 16