3

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

If the response comes back as:

<?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>

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

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.

Thanks,

R.

Richard
  • 5,810
  • 6
  • 29
  • 36
  • Worth adding, the service is fine. If I run var contacts = new WebClient().DownloadString(" http:// localhost:9000/api/contacts"); I get the XML file no worries. – Richard Dec 08 '11 at 05:26
  • I would use Linq to Xml. See [this question][1] for some examples. [1]: http://stackoverflow.com/questions/670563/linq-to-read-xml – Lloyd Dec 08 '11 at 12:09

2 Answers2

6

WCF Web API comes with a new, improved HttpClient implementation. Please take a look at this sample (which is included in the source code you can download here).

[Update]

var client = new HttpClient();
var task = client.GetAsync("http://webapi/Contacts");
var contacts = task.ContinueWith(
    t => {
        return t.Result.Content.ReadAsAsync<List<Contact>>();
    }).Unwrap().Result;

Console.WriteLine(contacts.Count);
Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
  • That looks good but how do I map the xml in the response to my strongly typed objects? – Richard Dec 08 '11 at 22:23
  • You can access the Content property of the response and call the ReadAsAsync where T is your type. HttpClient uses the build in XmlFormatter to deserialize your Xml. – Alexander Zeitler Dec 08 '11 at 23:40
5

You could define a model:

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

and then consume:

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
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928