MattD
MattD

Reputation: 1364

What's the best way to call a REST API from MVC4

MVC4 provides a very simple way to return serialized objects from HTTP requests. What's the best way to call a REST or other JSON/XML API from an MVC4 application? I could construct an HTTP request, send it, then deserialize the result, but I was hoping for something simpler. My application runs on multiple servers and one server needs to talk to the other via the web API. So, both servers have the same class definitions. I'm hoping there is some fairly transparent way to get MVC to deserialize as cleanly as it serializes content.

Upvotes: 0

Views: 2282

Answers (1)

Jim K
Jim K

Reputation: 155

This is an example of how I call an MVC4 WebAPI from a WPF application. You should be able to adjust according to your needs. Hope this helps...

     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri("http://192.200.1.3:9594/");
     // Add an Accept header for JSON format.
     client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

     HttpResponseMessage response = await client.GetAsync("EmployeeTest/TestApi");

     if (response.IsSuccessStatusCode) {
        var employee = response.Content.ReadAsAsync<Employee>().Result;
        tbName.Text = employee.Name;
        tbPhone.Text = employee.Phone;
     }

Upvotes: 1

Related Questions