Skip to content

Demonstrates how get the weather data from a WebAPI from the .NET MAUI client.

Notifications You must be signed in to change notification settings

BethMassi/BlazorHybridWebAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BlazorHybridWebAPI

This sample demonstrates how get the weather data from a WebAPI exposed on the Blazor server app which is called from the .NET MAUI client. I started with the .NET MAUI Blazor Hybrid and Web template maui-blazor-web and moved the weather generator code from the Weather.razor component to a WeatherService on the server which implements IWeatherService. This interface is injected into the Weather.razor component so that it calls the code directly on the server but uses the httpClient on the .NET MAUI Client.

IWeatherService.cs in the Shared RCL

public interface IWeatherService
{
Task<WeatherForecast[]> GetWeatherForecastAsync(DateTime startDate);
}

Weather.razor page

@page "/weather"
@using BlazorHybridWebAPI.Shared.Models
@using BlazorHybridWebAPI.Shared.Services
@inject IWeatherService WeatherService

...UI code is the same...

@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await WeatherService.GetWeatherForecastAsync(DateTime.Now);
}
}

WeatherService.cs on the Blazor web app

public class WeatherService : IWeatherService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public async Task<WeatherForecast[]> GetWeatherForecastAsync(DateTime startDate)
{
// Simulate a delay for async operation so we can see the loading spinner
await Task.Delay(1000);
var rng = new Random();
return await Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(startDate.AddDays(index)),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray());
}
}
}

WeatherService.cs on the .NET MAUI client

Note that this class uses an HttpClientHelper class that manages the HttpClient configuration for use while debugging on simulators and emulators.

namespace BlazorHybridWebAPI.Services
{
public class WeatherService : IWeatherService
{
public async Task<WeatherForecast[]> GetWeatherForecastAsync(DateTime dateTime)
{
var forecasts = Array.Empty<WeatherForecast>();
try
{
var httpClient = HttpClientHelper.GetHttpClient();
var weatherUrl = $"{HttpClientHelper.WeatherUrl}?startDate={dateTime.ToShortDateString()}";
forecasts = (await httpClient.GetFromJsonAsync<WeatherForecast[]>(weatherUrl)) ?? [];
}
catch (HttpRequestException httpEx)
{
Debug.WriteLine($"HTTP Request error: {httpEx.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"An error occurred: {ex.Message}");
}
return forecasts;
}
}
}

MauiProgram.cs

We need to add the service implementation to the builder:

builder.Services.AddScoped<IWeatherService, WeatherService>();

Program.cs on the Blazor web app

We need to add the service implementation to the builder:

builder.Services.AddScoped<IWeatherService, WeatherService>();

As well as expose the weather API:

app.MapGet("/api/weather", async (IWeatherService weatherService, DateTime startDate) =>
{
var forecasts = await weatherService.GetWeatherForecastAsync(startDate);
return Results.Ok(forecasts);
});

About

Demonstrates how get the weather data from a WebAPI from the .NET MAUI client.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published