ASP.NET MVC > Web API

Consuming external Web API in ASP.NET MVC in ASP.NET MVC

How to consume external Web API in ASP.NET MVC?


To consume external Web API in ASP.NET MVC (server side), we need to take help of HttpClient object exists into System.Net.Http namespace. Here we are assuming that the Web API is returning json data that it generally does.

CONTROLLER CODE

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 the above method, we are instantiating the HttpClient object and setting its BaseAddress. After that we are clearing any default request headers so that we can set our own header of “application/json”.

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). Now 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, read how to use 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.

CONSUMEEXTERNALAPI.CSHTML VIEW CODE

@{
    ViewBag.Title = "ListDataInGridView";
}

<h2>List Data In GridView</h2>

@Html.Raw(ViewBag.GridViewString)

In the view, we are simply using @Html.Raw method to write the GridView content set into the Action method. If we do not use @Html.Raw method, the output will be the HTML encoded characters so it will instead of bringing records into tabular format in the browser will simply writes the html table, rows and columns source code as output on the browser. So do not forget to use @Html.Raw while writing the html content to the view.

OUTPUT

 Views: 32504 | Post Order: 127



Write for us






Hosting Recommendations