Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C++

5 Simple Steps for Using Web API in ASP.NET Web Forms Application

Rate me:
Please Sign up or sign in to vote.
4.95/5 (8 votes)
13 May 2014CPOL3 min read 84.9K   10   2
5 simple steps for using web API in ASP.NET web forms application

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, 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 posts that you can refer to. 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:

C#
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.

C#
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:

C#
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 seen above, your ASP.NET Web API returns 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.

C#
<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:

C#
// 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, the above step by step approach will be helpful in building Web API with ASP.NET Web Forms application.

Other Recommended Articles

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

Comments and Discussions

 
QuestionConcise and accurate Pin
Member 1095521015-Jul-15 23:56
Member 1095521015-Jul-15 23:56 
QuestionFacing issue in Step 4 & 5 Pin
Member 1124620117-Dec-14 23:12
Member 1124620117-Dec-14 23:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.