Consuming WebApi in MVC3

Richard picture Richard · Dec 8, 2011 · Viewed 8.2k times · Source

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.

Answer

Alexander Zeitler picture Alexander Zeitler · Dec 8, 2011

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);