ASP.Net Web API with ASP.Net Web Forms

ASP.Net Web API with ASP.Net Web Forms
4 votes, 4.00 avg. rating (81% score)

Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. Tutorial for using Web API with Asp.Net Web Forms


To use Web API in a Web Forms application, there are two main steps:

  • Add a Web API controller that derives from the ApiController class.
  • Add a route table to the Application_Start method.

Create a Web Forms Project

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Forms Application. Enter a name for the project and click OK.

Create the Model and Controller

First, add a model class. In Solution Explorer, right-click the project and select Add Class. Name the class Product, and add the following implementation:

public class Product
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }

Next, add a Web API controller to the project., A controller is the object that handles HTTP requests for Web API.

In Solution Explorer, right-click the project. Select Add New Item.

Under Installed Templates, expand Visual C# and select Web. Then, from the list of templates, select Web API Controller Class. Name the controller "ProductsController" and click Add.

The Add New Item wizard will create a file named ProductsController.cs. Delete the methods that the wizard included and add the following methods:

namespace WebForms
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    public class ProductsController : ApiController

        Product[] products = new Product[] 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 

        public IEnumerable<Product> GetAllProducts()
            return products;

        public Product GetProductById(int id)
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return product;

        public IEnumerable<Product> GetProductsByCategory(string category)
            return products.Where(
                (p) => string.Equals(p.Category, category,

For more information about the code in this controller, see the Getting Started tutorial.

Add Routing Information

Next, we’ll add a URI route so that URIs of the form "/api/products/" are routed to the controller.

In Solution Explorer, double-click Global.asax to open the code-behind file Global.asax.cs. Add the following usingstatement.

using System.Web.Http;

Then add the following code to the Application_Start method:

    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }

For more information about routing tables, see Routing in ASP.NET Web API.

Add Client-Side AJAX

That’s all you need to create a web API that clients can access. Now let’s add an HTML page that uses jQuery to call the API.

Open the file Default.aspx. Replace the boilerplate text that is in the main content section, as shown:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <tbody id="products">

Next, add a reference to the jQuery source file in the HeaderContent section:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

Note: You can easily add the script reference by dragging and dropping the file from Solution Explorer into the code editor window.

Below the jQuery script tag, add the following script block:

<script type="text/javascript">
    function getProducts() {
            function (data) {
                $('#products').empty(); // Clear the table body.

                // Loop through the list of products.
                $.each(data, function (key, val) {
                    // Add a table row for the product.
                    var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
                    $('<tr/>', { text: row })  // Append the name.


When the document loads, this script makes an AJAX request to "api/products". The request returns a list of products in JSON format. The script adds the product information to the HTML table.

When you run the application, it should look like this:


I am fan of using ajax calls where ever required as I do not want to load the whole page data / requests everytime. ASP.Net Web api is good quick platform to integrate with any web application rather than just thinking migrating whole application to MVC. This is cross post from Mike Wasson who is Microsoft Writer, absolute quick start and very good one

June 1, 2015 В· Adi В· No Comments
Tags: , ,  В· Posted in: Asp.Net Web API, C#

Leave a Reply

What is 3 + 13 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)