I have not done this before, so need some leads. I have a ASP.NET MVC4 (beta) project - Mobile project - setup. And I am given a set of REST APIs to consume. How would I do this? The APIs return data in JSON format. Do you have any examples, best practices...?
2 Answers
You could use the $.ajax method to send an AJAX request to the Web Api controller on the server:
$.ajax({
url: 'api/values/123',
type: 'GET',
success: function(data) {
// if the controller returned JSON data, the data argument
// will represent a javascript object that you could directly
// access its properties
}
});
3 Comments
Rajeev Nair
Thanks Darin. So how do I consume the data in ASP.NET MVC? The examples show that I don't need "ASP.NET MVC"-ish code to use the data... all that we need is jQuery. Am I right?
Darin Dimitrov
Yes, you are right. If you want to consume the service from the client side you use javascript. If you want to consume it from a web application you could use the HttpClient which is the client framework of the Web API: johnnycode.com/blog/2012/02/23/…
Rajeev Nair
Thanks Darin. Marked as answer.
Use DownloadString method of WebClient class. That will give you a string output of what the RESTURL is returning. You can convert that to Json and iterate the results
string address="http://yourrestdomain/customer/234";
WebClient client = new WebClient ();
string reply = client.DownloadString (address);