0

Following JQuery code gets contacts from local web api. But, I wonder how to call external WEB API from SERVER SIDE?

$(function () {
            $.getJSON('/api/contact', function (data) {
                $(data).each(function (i, item) {
                    $('#contacts').append('<li>' + item.Name + '</li>');
                });
            });
});
tereško
  • 58,060
  • 25
  • 98
  • 150
mrd
  • 2,095
  • 6
  • 23
  • 48
  • 1
    Have a look at the HttpClient class: http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx – Allov Sep 19 '14 at 13:31

2 Answers2

0

You can make use of System.Net.WebClient to get the result from the WebApi. This is presuming you are using .Net 4.5 or above.

So your code would look something like;

WebClient webClient = new WebClient();
var result = webClient.DownloadString("[YourUrl]");

The result is the going to be a Json string, so you would then want to Deserialize the string to an Object.

So if you were to then use Newtonsoft.Json you could deserialize like;

MyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(result);
Tim B James
  • 20,084
  • 4
  • 73
  • 103
0

to get really async fuctionality by calling remote servers from your application, you should use DownloadStringTaskAsync method instead of syncronous DownloadString. Here is a good question about it.

And example from there:

private async void RequestData(string uri, Action<string> action)
{
    var client = new WebClient();
    string data = await client.DownloadStringTaskAsync(uri);
    action(data);
}
Community
  • 1
  • 1
aleha_84
  • 8,309
  • 2
  • 38
  • 46