我正在尝试使用. NET MAUI实现一个小应用程序,但在运行时不断出现错误System.Net.WebException:无法解析主机"http://www.example.com":没有与主机名关联的地址reqres.in": No address associated with hostname'有时我收到的错误听起来像:System.InvalidCastException:'指定的转换无效。'为了显示响应,我使用了ListView控件,最后使用了CollectionView我使用Nuget软件包管理器安装了Newtonsoft.Json。代码隐藏文件包含以下代码: private const string url = "https://reqres.in/api/users";
private HttpClient _Client = new HttpClient();
private ObservableCollection userCollection;
protected override async void OnAppearing()
{
base.OnAppearing();
var httpResponse = await _Client.GetAsync(url);
if (httpResponse.IsSuccessStatusCode)
{
Response responseData = JsonConvert.DeserializeObject(await httpResponse.Content.ReadAsStringAsync());
userCollection = new ObservableCollection(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 Users { get; set; }
}XAML文件的内容为:
|