0

如果我想在这里打电话: http ://thegamesdb.net/api/GetGamesList.php?name=x-men

我有以下两个类,我目前正在使用XMLDocument它来解析我的响应:

        public class Data
        {
           private IEnumerable<Game> Game { get; set; } 
        }

        public class Game
        {
            public int id { get; set; }
            public string GameTitle { get; set; }
            public DateTime ReleaseDate { get; set; }
            public string Platform { get; set; }
        }

我是否可以通过使用 ASP.NET Web API 进行调用来简化事情,并让它自动绑定到我的模型?还是这仅适用于从 发送数据ApiController

4

1 回答 1

1

当然,只需安装 Microsoft.AspNet.WebApi.Client 包 - http://nuget.org/packages/Microsoft.AspNet.WebApi.Client/4.0.20710.0

现在您可以调用外部服务并直接读入您的对象:

var client = new HttpClient();
var response = await client.GetAsync("http://thegamesdb.net/api/GetGamesList.php?name=x-men");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsAsync<Data>();
    foreach (var game in data.Game)
    {
        Console.WriteLine("{0}\t{1};\t{2}", game.Id, game.GameTitle, game.Platform);
    }
}

编辑:

鉴于 XML 具有非标准的集合格式,请执行以下操作:

[XmlRoot("Data")]
public class Data
{
    [XmlElement("Game")]
    public List<Game> Games { get; set; }
}

[XmlType("Game")]
public class Game
{
    public int id { get; set; }
    public string GameTitle { get; set; }
    public string ReleaseDate { get; set; }
    public string Platform { get; set; }
}

和:

    var client = new HttpClient();
    var response = await client.GetAsync("http://thegamesdb.net/api/GetGamesList.php?name=x-men");
    if (response.IsSuccessStatusCode)
    {
        var games = await response.Content.ReadAsAsync<Data>(new HashSet<MediaTypeFormatter>() { new XmlMediaTypeFormatter {UseXmlSerializer = true} });
        foreach (var game in games.Games)
        {
            Console.WriteLine("{0}\t{1};\t{2}", game.id, game.GameTitle, game.Platform);
        }
    }

我们需要提示XmlSerializer如何处理真正以属性形式发送给您的数组。此外,它们的日期无效,因此您应该将其保存为字符串(或在 setter 中解析)。

另外,由于我们使用XmlSerializernot DataContractSerializer,您不能使用IEnumerable,它必须是List<T>

于 2013-02-03T03:06:19.423 回答