In this article, we are going to learn how to consume external Web API in ASP.NET MVC.
Introduction
Web API has become integral part of the web development now and most of the services now are exposed via Web API as against Web Services. Web API mainly returns light weight JSON formatted data (it can also return XML) that can be easily converted into object and easily understood by JavaScript to manipulate and iterate. Web API is based on HTTP is very light weight and perform much better than Web Services where SOAP is used to transfer the data and convert back to request - response.
Using the code
To explain, how to consume external Web in ASP.NET MVC, we have a sample controller action method below.
public async System.Threading.Tasks.Task<ActionResult> ConsumeExternalAPI()
{
string url = "http://someurl.com//api/PersonalDetails/GetPersonalDetails";
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);
System.Web.UI.WebControls.GridView gView = new System.Web.UI.WebControls.GridView();
gView.DataSource = table;
gView.DataBind();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))
{
gView.RenderControl(htw);
ViewBag.ReturnedData = sw.ToString();
}
}
}
}
return View();
}
Notice that the return type of this action method is Task<ActionResult> (it means that this action method can get executed asynchronously) as external Web API response is dependent on the network traffic and it is RESTFUL in nature.
In the above method, we are instantiating the HttpClient object and setting its BaseAddress to the URL of the Web API we need to consume. In general the, URL contains the necessary credentials in the form of querystring to allow to connect to the API (like username, password, parameter to pass etc.)
After that we are clearing any default request headers so that we can set our own header of “application/json”. Here we are assuming that the external Web API returns data in json format.
Next, we are getting the response from the API by calling client.GetAsync() method. If the status code is success we are reading the content string returned from the API (ie. the json string) into data
variable.
After that we are converting the json string into DataTable using JsonConvert.DeserializeObject method (In case the project doesn’t contains Newtonsoft.json namespace, we need to install the assembly through Manage NuGet Packages).
Once the json data is converted into DataTable, we are setting it to the GridView and setting the GridView rendered string into ViewBag that gets written on the View.
To consume API that returns data other than json format, we need to pass MediaTypeWithQualityHeaderValue to something else (like "application/xml" etc.).
Conclusion
You can see that how easy it is now to consume any external Web API into ASP.NET MVC. The local API that exists into the same project can be simply consume via jQuery AJAX method as it remains on the same server and no credentials may be required to connect to them. However consuming external API need credentials to be passed and jQuery can't be used as browser restricts the cross domain request through client side.
Thanks for reading, do write your comments or suggestions about this article by responding it. For more ASP.NET Real time problem solutions,
click here.