5 simple steps for using Web API with ASP.NET Web Forms Application

By | May 12, 2014

I have seen this question more than once while going through different ASP.NET web forums that “Is it possible to use Web API with ASP.NET Web Forms Application?” Simple answer to the question is “YES, we can“.
Let’s discuss about it in more details. As we already know that Microsoft released ASP.NET MVC 4 with lots of new and exciting features including ASP.NET Web API which is basically a framework for building HTTP services that reaches broader range of clients including browsers as well as mobile devices. But it’s flexible enough to be used with ASP.NET Web Forms applications. In this ASP.NET Tutorial, we are using a step by step approach for using Web API with ASP.NET Web Forms. For a good comparison of features released in each version of ASP.NET MVC, click here.I have already implemented an HTTP service using ASP.NET Web API in one of my previous post that you can refer here. Adding a Model and a Controller is same but the difference is that we are adding it to ASP.NET Web Forms Application. So, let follow the steps as below:

  1. Create a New Web Forms Application.
  2. Add Model to Web Forms Application.
  3. Add Controller to Application.
  4. Add Routing Info to Global.asax.
  5. Making a Client Call.
For the purpose of implementation, I am using Visual Studio Express 2013 for Web here.

1. Create a New Web Forms Application

  • Open Visual Studio and create “New Project” i.e. File -> New Project.
  • Choose “ASP.NET Web Application” template and name project as “WebAPIwithWebForms”.
  • When you click “OK” button, a new window will appear for selecting a sub-template.
    Note: You may not get window for sub-template in older versions of Visual Studio.
  • Choose “Web Forms” and click “OK”.
Using Web API with Web Forms
  • An ASP.NET Web Forms template project is created.

2. Add Model

Now we need to add a new class that acts as a Model in our application as follows:
ASP.NET Web API Model
Web API Model
Following is the code for Student Model
    public class Student
    {
        public int StudentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

3. Add Controller class

Controller class has special importance because request coming from client reaches the controller first. Then the controller decides which model to use in order to serve the incoming request.
Right click on the project and choose “Web API Controller” under “Add” from the context menu as shown in figure.
ASP.NET Web API Controller
Web API Controller
Name the controller as “StudentsController” and press “OK” button.
For the purpose of simplicity, I’ll load the model with data inside our “StudentsController” instead of loading directly from database. Following is the code for StudentsController inheriting from ApiController class.
public class StudentsController : ApiController
{
        Student[] students = new Student[]
         {
             new Student { StudentID = 1, FirstName = “Imran”, LastName = “Ghani” },
             new Student { StudentID = 2, FirstName = “Salman”, LastName = “Ahmad” },
             new Student { StudentID = 3, FirstName = “Rehan”, LastName = “Ahmad” },
             new Student { StudentID = 4, FirstName = “Zeeshan”, LastName = “Khalid” }
         };
        public IEnumerable<Student> GetStudents()
        {
            return students;
        }
}

4. Add Routing Info to Global.asax

In order to route incoming request directly to our StudentsController, we need to add Route Information to Application_Start method of Global.asax as given below:
RouteTable.Routes.MapHttpRoute(
          name: “DefaultApi”,
          routeTemplate: “api/{controller}/{id}”,
          defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

Now, if you run your application and try to access the following URL, you will get a JSON response of student data from api controller. Try to access the following URL and see:

             http://localhost:xxxx/api/Students

Note: Don’t forget to add “using System.Web.Http” in Global.asax.cs file.

5. Make a Client Call

As you have already see above your ASP.NET Web API returning data in JSON format. Now, let’s call it from your Web Form using jQuery and display it on your Web Form page.
Create a new Web Form page “WebFormClient” and add the following code to call your ASP.NET Web API Controller i.e. “StudentsController” using jQuery.Main content area will contain the following HTML for rendering Students data.

<table border=’1′ id=”students”>
       <!– Make a Header Row –>
       <tr>
            <td><b>StudentID</b></td>
            <td><b>FirstName</b></td>
            <td><b>LastName</b></td>
        </tr>
</table>

using jQuery, make a call to our controller and fetch data as follows:
// GET ALL

function GetAllStudents()
{
           $.ajax({
                       type: “GET”,
                       url: “http://localhost:xxxx/api/Students/”,
                       contentType: “json”,
                       dataType: “json”,
                       success: function (data) {
                                  $.each(data, function (key, value) {
                                  //stringify
                                  var jsonData = JSON.stringify(value);
                                 //Parse JSON
                                 var objData = $.parseJSON(jsonData);
                                 var id = objData.StudentId;
                                 var fname = objData.FirstName;
                                 var lname = objData.LastName;                                $(‘<tr><td>’ + id + ‘</td><td>’ + fname +
                                       ‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);

                       });
             },
             error: function (xhr) {
                         alert(xhr.responseText);
            }
     });
}

Hopefully, above step by step approach will be helpful in building Web API with ASP.NET Web Forms Application.

Other Related Web Development Articles:

Top 10 Interview Questions and Answers Series: