In this article I will explain with an example, how to call Web API 2 Controller method using HttpWebRequest class in ASP.Net with C# .Net.
The Web API 2 Controller method will fetch records from database using Entity Framework in ASP.Net MVC and later it will be called (consumed) in ASP.Net Web Forms (ASPX) page using HttpWebRequest class in ASP.Net.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Call (Consume) Web API using HttpWebRequest in ASP.Net C#
 
 
Model
The CustomerModel class consists of the following property.
public class CustomerModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
}
 
 
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Call (Consume) Web API using HttpWebRequest in ASP.Net C#
 
Then give it a suitable name and click OK.
Call (Consume) Web API using HttpWebRequest in ASP.Net C#
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller. The Web API Controller consists of a method named GetCustomers which accepts an object of CustomerModel.
The records of the Customers are fetched using Entity Framework and are filtered using the StartsWith function based on the value of the Name property.
Finally the records are returned as Generic List Collection.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
public class CustomerAPIController : ApiController
{
    [Route("api/CustomerAPI/GetCustomers")]
    [HttpPost]
    public List<Customer> GetCustomers(CustomerModel customer)
    {
        NorthwindEntities entities = new NorthwindEntities();
        return (from c in entities.Customers.Take(10)
                where c.ContactName.StartsWith(customer.Name) || string.IsNullOrEmpty(customer.Name)
                select c).ToList();
    }
}
 
 
The Web Form
Now you will need to add a Web Form page to your MVC Web Application using Add New Item dialog as shown below.
Call (Consume) Web API using HttpWebRequest in ASP.Net C#
 
 
HTML Markup
The following HTML Markup of the Web Form consists of an ASP.Net TextBox, a Button and a GridView.
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Search"/>
<hr/>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID"/>
        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name"/>
        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City"/>
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
 
 
Calling the Web API using HttpWebRequest class and populating the GridView
The PopulateGridView method is called inside the Page Load event handler and on the Click event handler of the Search button.
Inside the PopulateGridView method, the value of the Name TextBox is wrapped into a JSON object which is then serialized into a JSON string.
The URL of the Web API along with its Controller method is passed to the Create method of the HttpWebRequest class.
Next the ContentType and the Method properties are set for the HttpWebRequest class object and the serialized JSON string is converted into Byte Array and is posted to Web API using the GetRequestStream method of the HttpWebRequest class.
Finally the GetResponseStream method of the HttpWebRequest class returns the JSON string which is then de-serialized to Generic List of Customer class objects which is used to populate the GridView.
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.PopulateGridView();
    }
}
 
protected void Search(object sender, EventArgs e)
{
    this.PopulateGridView();
}
 
private void PopulateGridView()
{
    string apiUrl = "http://localhost:26404/api/CustomerAPI";
    var input = new
    {
        Name = txtName.Text.Trim(),
    };
    string inputJson = (new JavaScriptSerializer()).Serialize(input);
    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl + "/GetCustomers"));
    httpRequest.ContentType = "application/json";
    httpRequest.Method = "POST";
 
    byte[] bytes = Encoding.UTF8.GetBytes(inputJson);
    using (Stream stream = httpRequest.GetRequestStream())
    {
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
    }
 
    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
        using (Stream stream = httpResponse.GetResponseStream())
        {
            string json = (new StreamReader(stream)).ReadToEnd();
            gvCustomers.DataSource = (new JavaScriptSerializer()).Deserialize<List<Customer>>(json);
            gvCustomers.DataBind();
        }
    }
}
 
public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}
 
 
Screenshot
Call (Consume) Web API using HttpWebRequest in ASP.Net C#
 
 
Downloads