using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
public class ApiService
{
    private readonly HttpClient httpClient;
    public ApiService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }
    public async Task GetAsync(string endpoint)
    {
        var response = await httpClient.GetAsync(endpoint);
        response.EnsureSuccessStatusCode(); // 异常处理
        var content = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize(content);
    }
}
   
@page "/"
@using System.Net.Http
Hello, world!
The current weather:
    @foreach(var item in weather)
    {
        - @item
 
    }
@code {
    private string[] weather;
    protected override async Task OnInitializedAsync()
    {
        var httpClient = new HttpClient();
        var apiService = new ApiService(httpClient);
        var endpoint = "https://api.openweathermap.org/data/2.5/weather?q=London&appid={your-app-id}";
        weather = await apiService.GetAsync(endpoint);
    }
}
 
该示例使用了 OpenWeatherMap API 来获取伦敦的天气。请记得将“{your-app-id}”替换为您自己的应用程序 ID。