我可以将ASP.NET Web API模型绑定用于外部服务吗?

时间:2013-02-03 02:20:58

标签: .net asp.net-web-api

如果我想打电话到这里: 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发送数据?

1 个答案:

答案 0 :(得分: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中解析)。

此外,由于我们使用的是XmlSerializer而不是DataContractSerializer,因此您无法使用IEnumerable,它必须是List<T>