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.

You are designing an ASP.NET Web API application. You need to select an HTTP verb to allow blog administrators to moderate a comment. Which HTTP verb should you use?

  • A. GET
  • B. POST
  • C. DELETE
  • D. PUT

To further test your ASP.NET Web API skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.

 Correct Answer: D

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:

Latest Developers Jobs

Top ASP.NET MVC Jobs

GIS Developer
Source: Indeed
Details: ASP.Net MVC – VB.Net and C#. Geospatial Solutions Developer Junior -10892....  More
23 hours ago

Madison, WI 29-August-2016

.Net Developer
Source: Indeed
Details: MVC. We are looking for a few well rounded developers to help with our .Net web development applications....  More
3 days ago

Carrollton, GA 30117 26-August-2016

Fulltime- Perm Jr/Mid level. Front end developer
Source: Indeed
Details: JQuery, Knockout.js, etc.)ASP.NET MVC, Entity Framework. A proven track record of developing websites using technologies such as HTML5, CSS3, JavaScript, AJAX,...  More
4 days ago

Boston, MA 25-August-2016

.NET Developer
Source: Indeed
Details: ASP.NET MVC 4+, Web API, Fluent Nhibernate. Software Analysis, Design, Development, and maintain modern web applications using a mix of open source and closed...  More
4 days ago

Rogers, AR 72756 25-August-2016

Software Engineer
Source: Clarity Consulting
Details: C# / WinRT / .NET / XAML / Windows 8/8.1/10 / Windows Phone 8/8.1 / Xbox / iOS / Cocoa Objective-C / Android / HTML5 / JavaScript/jQuery / CSS3 / ASP.NET MVC /...  More
13 days ago

Seattle, WA 16-August-2016

Junior Developer
Source: Indeed
Details: Experience with ASP.net MVC. We are looking for a junior developer to create and maintain existing .net desktop and web applications....  More
10 days ago

Albuquerque, NM 19-August-2016

ASP.NET Developer - onsite/remote/FT/Contract
Source: Indeed
Details: Familiarity with ASP.net, MVC, SQL, HTML, JavaScript and CSS is helpful. GeekHive is looking to expand its team and has opportunities for full-stack, back-end...  More
10 days ago

Warwick, NY 10990 19-August-2016

.Net/Software Developer
Source: Indeed
Details: Have worked with ASP.NET, MVC*. Design ASP type pages for both display and server processing*. Develop programs for Global Treasury Manager project....  More
10 days ago

Hartford, CT 19-August-2016

Mid-Level Software Developer - .NET
Source: Indeed
Details: Develop new and maintain existing software using the ASP.NET / MVC platform. Demonstrated experience developing web-based applications using .Net framework 3.5...  More
11 days ago

San Diego, CA 18-August-2016

Sr .Net Developer
Source: Adept Solutions
Details: ASP.NET MVC development experience (4 yrs minimum) C# development experience (4 yrs minimum) SQL Server 2012 development & support experience (4 yrs minimum)....  More
19 days ago

Dearborn, MI 48120 11-August-2016

Software Engineer II
Source: Indeed
Details: 3+ years experience, Microsoft .Net, C# and ASP.Net MVC. The Development Team....  More
18 hours ago

Irvine, CA 29-August-2016

Full Stack Developer
Source: Graphic Products
Details: Proficient knowledge of ASP.NET MVC 5+. We are looking for a Full Stack Developer responsible for the ongoing development and advancements of our ecommerce and...  More
18 days ago

Beaverton, OR 97008 11-August-2016

Here we grow again-Software Engineer
Source: Indeed
Details: Experience in building ASP.NET MVC applications. This is a full time position as a Software Engineer with a major financial company in downtown Detroit....  More
3 days ago

Detroit, MI 26-August-2016

Application Developer - Secret Clearance Required
Source: Indeed
Details: ASP.NET MVC, Entity Framework (or other ORM), JavaScript, XML, JSON, Web API, and Powershell. (SECRET Clearance Required)*....  More
18 days ago

Reston, VA 11-August-2016

Consulting Software Engineer
Source: Indeed
Details: MVC 3/4, Unit Testing/MS Unit, TFS, JavaScript, AJAX. This position provides assistance and input to management, develops and leads large multi functional...  More
30+ days ago

Raleigh, NC 12-July-2016

Software Reverse Engineer
Source: Indeed
Details: Minimum 5 years development background using C#, ASP.NET, MVC, WPF. Software Reverse Engineer*....  More
4 days ago

Columbus, OH 25-August-2016

.Net Developer
Source: Indeed
Details: Knowledge of ASP.NET MVC. Knowledge of Object Oriented (OO) design patterns....  More
12 days ago

Columbia, MD 18-August-2016

Software Engineer
Source: Indeed
Details: C# -ASP.Net MVC 5+. THIS IS A DIRECT HIRE ROLE - NO C2C PLEASE!*....  More
4 days ago

Birmingham, AL 25-August-2016

.Net Developer
Source: Indeed
Details: C# • .NET 4.0, ASP.NET MVC 4 with Razor Templates • MS Unity • MS Visual Studio• OO Design Patterns • Web Services, REST, JSON, AJAX • JavaScript, JQuery • XML,...  More
19 days ago

Rochester, NY 10-August-2016

Apple, Android, C#, cross-platform mobile developer
Source: Indeed
Details: C# .Net web development (Windows phone, C# Xamarin cross-platform mobile development, ASP.NET MVC Framework)....  More
19 days ago

Miami, FL 33132 10-August-2016

Mid-Level .Net Developer
Source: Centare
Details: ASP.NET MVC or WebForms. We are currently looking to add a Mid-Level .Net Developer to our team in Madison....  More
20 days ago

Madison, WI 09-August-2016

.NET Sr.Consultant.
Source: Indeed
Details: C# development and .NET technology, including ASP.NET MVC is big plus. Full time after 6 Months Contract (Contract to Hire)....  More
21 hours ago

Dallas, TX 29-August-2016

16-03-108 Software Engineer- Web development
Source: Indeed
Details: Working knowledge of .NET including C#, ASP.NET MVC, and ADO.NET, required. This is a key position within the Avastone Technologies organization responsible for...  More
6 days ago

Little Chute, WI 54140 23-August-2016

Software Engineer
Source: Indeed
Details: ChoiceOne EHR, Inc. was founded in 2008 by long time veterans of the medical practice administration and medical billing industry. Because ChoiceOne EHR, Inc.  More
7 days ago

Cerritos, CA 22-August-2016

Software Engineer C#/ASP.NET MVC/JavaScript
Source: Cormant, Inc.
Details: You will be working on full stack development including Marionette client, and a C# MVC architecture with NHibernate/RDBMS as the back-end....  More
8 days ago

San Luis Obispo, CA 22-August-2016
Category: ASP.NET Web API ASP.NET Web Forms Tags: ,

About IMRAN ABDUL GHANI

Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several 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 www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.