How to Consume Web API Using Web Request

This article explains how to consume a Web API using a Web Request and deserialize it in JSON and bind data in a grid view.

This article explains how to consume a Web API using a Web Request and deserialize it in JSON and bind data in a grid view.

Getting Started

Create a new project in Visual Studio 2012 and select "Empty ASP.NET Web Application" and click "OK".

First of all add two classes:

public class wrapper


    public List<SalesPerson> salesperson { get; set; }



public class SalesPerson


    public String Code { get; set; }

    public String databaseID { get; set; }   

    public String name { get; set; }

    public String path { get; set; }

    public String definition { get; set; }


Now add your web api URL:

string _URL = "";

Now drag and drop a GridView data control onto the page.

Now add these namespaces:

using System.IO;

using System.Web.Script.Serialization;

protected void Page_Load(object sender, EventArgs e)

       WebRequest req = WebRequest.Create(_URL);
       req.Method =
req.ContentType =
"application/json; charset=utf-8"

WebResponse resp = req.GetResponse(); 
stream = resp.GetResponseStream();

StreamReader re = new StreamReader(stream);

String json = re.ReadToEnd();

json = "{\"SalesPerson\":" + json + "}";

wrapper w = (wrapper)new JavaScriptSerializer().Deserialize(json, typeof(wrapper));

        GridView1.DataSource = w.salesperson;





<asp:GridView ID="GridView1" runat="server" Width="500px" CellPadding="4" ForeColor="#333333" GridLines="None" EmptyDataText="Data Not Found">

    <AlternatingRowStyle BackColor="White" />

    <EditRowStyle BackColor="#7C6F57" />

    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />

    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />

    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />

    <RowStyle BackColor="#E3EAEB" />

    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

    <SortedAscendingCellStyle BackColor="#F8FAFA" />

    <SortedAscendingHeaderStyle BackColor="#246B61" />

    <SortedDescendingCellStyle BackColor="#D4DFE1" />

    <SortedDescendingHeaderStyle BackColor="#15524A" />


Now run the application to see the output.


Image 1.