blazor_dotnet10

Blazor .NET 10 with Minimal API

blazor_dotnet10

.NET 10: .NET 10 is the latest version of the .NET framework, which provides a robust platform for building web applications, services, and more.

Blazor: Blazor is a web framework that enables developers to create client-side web applications using C#. It leverages WebAssembly to run C# code directly in the browser, allowing for a rich interactive experience without relying on JavaScript. Blazor can be used in two modes: Blazor Server and Blazor WebAssembly.

Minimal API: Minimal APIs in .NET 10 provide a streamlined approach to building HTTP APIs. They allow developers to define routes and handle requests with minimal boilerplate code, making it easier to create lightweight services. This is particularly beneficial for microservices and small applications where simplicity and speed are paramount.

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    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 forecast;
})
.WithName("GetWeatherForecast");

app.Run();

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

WeatherForecast record defines the structure of the weather data, including a computed property to convert Celsius to Fahrenheit.
GET endpoint at /weatherforecast, it generates an array of five weather forecasts, each with a date, a random temperature, and a random summary. The WeatherForecast record is instantiated for each forecast.

Weather.razor
@page "/weather"
@inject HttpClient Client

<PageTitle>Weather</PageTitle>

<h1>Weather</h1>

<p>This component demonstrates showing data.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th aria-label="Temperature in Celsius">Temp. (C)</th>
                <th aria-label="Temperature in Fahrenheit">Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync()
    {
        // Simulate asynchronous loading to demonstrate a loading indicator
        await Task.Delay(500);

        // https://localhost:6001/weatherforecast
        forecasts = await Client.GetFromJsonAsync<WeatherForecast[]>("weatherforecast") ?? [];

        // var startDate = DateOnly.FromDateTime(DateTime.Now);
        // var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
        // forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        // {
        //     Date = startDate.AddDays(index),
        //     TemperatureC = Random.Shared.Next(-20, 55),
        //     Summary = summaries[Random.Shared.Next(summaries.Length)]
        // }).ToArray();
    }

    private class WeatherForecast
    {
        public DateOnly Date { get; set; }
        public int TemperatureC { get; set; }
        public string? Summary { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}

Page Directive: The @page "/weather" directive specifies that this component will be accessible at the /weather URL.
Dependency Injection: The @inject HttpClient Client line allows the component to use the HttpClient service for making HTTP requests.
Data Table: Once the data is loaded, a table is rendered displaying the date, temperature in Celsius and Fahrenheit, and a summary of the weather.
WeatherForecast Class: This class defines the structure of the weather data, including properties for date, temperature in Celsius, summary, and a calculated property for temperature in Fahrenheit.

Source

Full source code is available at this repository in GitHub:
https://github.com/akifmt/DotNetCoding/tree/main/src/BlazorAppNET10withMinimalAPI