在消费MVC3的WebAPI [英] Consuming WebApi in MVC3

查看:151
本文介绍了在消费MVC3的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的WebAPI,什么是一个MVC客户端使用服务的最佳方式?

Using WebApi, what is the best way to consume a service in a MVC client?

如果响应回来为:

<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfContact 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Contact>
        <Id>1</Id>
        <Name>Bilbo Baggins</Name>
    </Contact>
    <Contact>
        <Id>2</Id>
        <Name>Frodo Baggins</Name>
    </Contact>
</ArrayOfContact>

我怎么能拿去,让我的联系方式,并在使用@Model列出他们在一个MVC3的Razor视图?

How can I take that, get my Contacts out and list them in a MVC3 Razor View using @Model?

有一个<一个href=\"http://wcf.$c$cplex.com/wikipage?title=Getting%20started%3a%20Building%20a%20simple%20web%20api\"相对=nofollow>很多例子在线获得的WebAPI的最新preVIEW,但我找不到任何更进了一步,并显示出客户的消耗的服务,说使用Web客户端。

There's a lot of examples online for the latest preview of WebApi but I can't find any that go a step further and show a client consuming the service, say using WebClient.

谢谢,

R上。

推荐答案

您可以定义一个模式:

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
}

然后消耗:

var url = "http://localhost:9000/api/contacts";
using (var client = new WebClient())
using (var reader = XmlReader.Create(client.OpenRead(url)))
{
    var serializer = new XmlSerializer(typeof(Contact[]));
    var contacts = (Contact[])serializer.Deserialize(reader);
    // TODO: Do something with the contacts
}

这篇关于在消费MVC3的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆