【发布时间】:2019-03-19 21:20:40
【问题描述】:
Xamarin.forms 的新手。
以下代码应生成游戏列表并将其绑定到列表视图,但它没有。我正在使用改装库。 Postman 中的 URL 按预期返回 JSON 列表。我应该从哪里开始?
ISteamService.CS
using System.Collections.Generic;
using System.Threading.Tasks;
using Refit;
namespace PatchNotes
{
[Headers("Content-Type: application/json")]
public interface ISteamService
{
[Get("/IPlayerService/GetOwnedGames/v1/?key=XXXXC&include_appinfo=1&steamid=XXXX")]
Task<string> GetGames();
}
}
MainPage.xaml.cs
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Forms;
using Refit;
namespace PatchNotes
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void OnGetGamesClicked(object sender, System.EventArgs e)
{
var apiResponse = RestService.For<ISteamService>("https://api.steampowered.com");
var games = await apiResponse.GetGames();
GamesList.ItemsSource = games;
}
}
}
MainPage.Xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="PatchNotes.MainPage">
<ContentPage.Content>
<StackLayout Padding="40">
<Button Text="Get Games" Clicked="OnGetGamesClicked"
BackgroundColor="Black" TextColor="White"
HorizontalOptions="FillAndExpand"/>
<ListView x:Name="GamesList">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
【问题讨论】:
-
对于 web api 和 xamrin forms 应用程序之间的故障排除问题,首先使 web api 工作。您可以使用 Postman (getpostman.com) 等工具测试您的 Web api。在这个阶段不需要使用 xamarin 表单应用程序。 Web api 正常工作后,您可以在 Visual Studio 中调试您的移动应用程序并查看问题所在。
-
GetGames 返回单个字符串值,但 ListView ItemsSource 必须是 IEnumerable(即数组/列表/集合)。我猜 GetGames 返回一个 json 数组,如果是这样,您需要告诉 Refit 将其反序列化为正确的类型
标签: c# rest api xamarin.forms