c# - 如何在 .NET MAUI 中发送和显示获取请求?

标签 c# xaml maui .net-maui

我正在尝试使用 .NET MAUI 实现一个小型应用程序,但我在运行时不断收到错误

System.Net.WebException: 'Unable to resolve host "reqres.in": No address associated with hostname'

有时我会收到听起来像这样的错误:

System.InvalidCastException: 'Specified cast is not valid.'

为了显示响应,我使用了 ListView 控件,最后使用了 CollectionView

我使用 Nuget 包管理器安装了 Newtonsoft.Json。

代码隐藏文件包含以下代码:

private const string url = "https://reqres.in/api/users";
private HttpClient _Client = new HttpClient();
private ObservableCollection<User> userCollection;

    protected override async void OnAppearing()
    {
        
        base.OnAppearing();

        var httpResponse = await _Client.GetAsync(url);

        if (httpResponse.IsSuccessStatusCode)
        {
            Response responseData = JsonConvert.DeserializeObject<Response>(await httpResponse.Content.ReadAsStringAsync());
            userCollection = new ObservableCollection<User>(responseData.Users);
            User_List.ItemsSource = userCollection;
        }
    }

public class User
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("first_name")]
    public string FirstName { get; set; }

    [JsonProperty("last_name")]
    public string LastName { get; set; }

    [JsonProperty("avatar")]
    public string AvatarURI { get; set; }

    public string FullName
    {
        get { return $"{FirstName} {LastName}"; }
    }
}

public class Response
{
    [JsonProperty("page")]
    public int Page { get; set; }

    [JsonProperty("per_page")]
    public int PerPage { get; set; }

    [JsonProperty("total")]
    public int Total { get; set; }

    [JsonProperty("total_pages")]
    public int TotalPages { get; set; }

    [JsonProperty("data")]
    public ObservableCollection<User> Users { get; set; }
}

XAML 文件的内容是:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="TabbedPageTest.TeamMembersPage"
         BackgroundColor="{DynamicResource SecondaryColor}">
  <StackLayout>
    <Label Text="Team Members"/>
    <CollectionView x:Name="User_List" HeightRequest="400" >
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <ImageCell ImageSource="{Binding AvatarURI}" Text="{Binding FullName}" Detail="{Binding Email}"/>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    <Button Text="Back" Clicked="OnBackButtonClicked" VerticalOptions="CenterAndExpand" />
  </StackLayout>
</ContentPage>

最佳答案

当我使用 ListView 控件而不是 CollectionView 时,应用程序成功运行并且没有显示错误。

我提到我使用了ListView控件,但我没有正确测试它。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TabbedPageTest.TeamMembersPage"
             BackgroundColor="{DynamicResource SecondaryColor}">
    <StackLayout>
        <Label Text="Team Members"/>
        <ListView x:Name="User_List" 
                  HeightRequest="400"
                  ItemSelected="OnListItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ImageCell ImageSource="{Binding AvatarURI}" Text="{Binding FullName}" Detail="{Binding Email}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Text="Back" Clicked="OnBackButtonClicked" VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage>

关于c# - 如何在 .NET MAUI 中发送和显示获取请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70621034/

相关文章:

c# - 在 MVVM 中动态创建控件

c# - 为什么数组协方差被认为如此可怕?

c# - 使用C#中的Specflow将测试失败消息发送给测试人员

c# - WPF 自定义窗口在设计时不应用其通用模板

c# - 在 View 模型中使用 XAML 资源

c# - C# 和深度复制中的 Elm 架构 (MVU)

c# - 这个 nameof() 真的是递归调用吗?

c# - 找出风格问题的原因

c# - .NET Maui MVVM Picker 绑定(bind) SelectedIndexChanged 事件

maui - 在 iOS 和 MacCatalyst 中无法单击 MAUI 底部附近的按钮