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

Junior .Net Developer
Source: Willis Towers Watson
Details: MVC experience preferred. You will also be responsible, to some extent, to maintain and customize our pre-BenefitConnect software, written in Visual Basic 6,...  More
14 days ago

Washington, DC 12-July-2016

Junior .Net Developer (TS w/SCI Eligibility Required)
Source: Indeed
Details: Experience with Web technologies such as Asp.Net Web forms, Asp.Net MVC, HTML, CSS, JavaScript and JQuery. Please do not use the Indeed application option....  More
21 days ago

Southern Pines, NC 05-July-2016

Junior .NET Developer
Source: Hobby Lobby
Details: ASP .NET MVC Experience - preferably MVC 4 and the Razor view engine. We are in search of an enthusiastic and self-motivated C# developer with 2 to 4 years of...  More
30+ days ago

Oklahoma City, OK 73179 08-June-2016

Senior Software Engineer
Source: Indeed
Details: 2+ years experience working with ASP.NET MVC. Our current platform is built leveraging ASP.NET MVC, C#, SQL Server, Entity Framework (Code First), and IoC / DI...  More
13 hours ago

Chicago, IL 60654 26-July-2016

Junior ASP.NET Developer
Source: Indeed
Details: *Job Overview* We are seeking a talented web developer to join our team in helping us manage our client’s website. *Responsibilities: * * Participate in full  More
30+ days ago

San Jose, CA 95112 23-June-2016

Sitecore Developer- Open To Any Experience Level
Source: Rightpoint
Details: Experience with ASP.NET MVC and/or Web Forms. Software Development | Chicago, IL, United States....  More
4 days ago

Chicago, IL 22-July-2016

Senior Software Engineer
Source: Indeed
Details: 5 to 7 years of experience with Microsoft .Net Framework, C#, javascript, JQuery, SQL, ASP.NET MVC, AngularJS. Required skills and experience:....  More
5 days ago

Bohemia, NY 21-July-2016

C# / ASP.NET Developer (FTE) (Dallas)
Source: Brand Protection Agency, LLC
Details: The developer will be exposed to the latest technologies such as WCF, ASP.NET, ASP.NET MVC, .NET 3.5 and 4.0, JavaScript, AJAX, JSON, ext-js and other open...  More
20 hours ago

Dallas, TX 26-July-2016

Sitecore Developer- Open To Any Experience Level
Source: Rightpoint
Details: Experience with ASP.NET MVC and/or Web Forms. Software Development | Dallas, TX, United States....  More
13 days ago

Dallas, TX 13-July-2016

Sitecore Developer- Open To Any Experience Level
Source: Rightpoint
Details: Experience with ASP.NET MVC and/or Web Forms. Software Development | Boston, MA, United States....  More
13 days ago

Boston, MA 13-July-2016

Sitecore Developer- Open To Any Experience Level
Source: Rightpoint
Details: Experience with ASP.NET MVC and/or Web Forms. Software Development | Atlanta, GA, United States....  More
13 days ago

Atlanta, GA 13-July-2016

Only GC & USC Need Sr .NET Developer @ Chicago IL
Source: Indeed
Details: Deep understanding of DOM, AJAX, HTTP, ASP.NET MVC. Qualified candidates will have JavaScript, DOM, AJAX, HTTP, ASP.NET MVC and HTML. Hi,....  More
1 day ago

Chicago, IL 25-July-2016

Junior .NET Developer
Source: Indeed
Details: Experience with C#, ASP.NET, MVC, HTML, JavaScript, Angular Js, Bootstrap. If you enjoy working with cutting edge technologies like C#, ASP.NET 5.0, MVC 5,...  More
30+ days ago

Chicago, IL 11-June-2016

.Net Architect
Source: Indeed
Details: Expertise in WCF, WebAPI, ASP .NET MVC. Greetings from Thinkloud Technologies Inc....  More
22 hours ago

Redmond, WA 26-July-2016

JUNIOR .NET DEVELOPER
Source: Harold Grinspoon Foundation
Details: 1+ years of experience with ASP.NET or ASP.NET MVC. The Harold Grinspoon Foundation, a results-driven, entrepreneurial non-profit organization headquartered in...  More
30+ days ago

Agawam, MA 09-June-2016

Web Services Developer
Source: Bell Integrator
Details: 6+ years’ experience developing .Net Web Services using ASP .Net MVC, Web API, C#, JSON. Experience with ASP .Net front end Web Development and three-tier...  More
7 days ago

United States 19-July-2016

C# Web Developer
Source: Indeed
Details: C#, ASP.net MVC, Web Services and MS Azure cloud development.:. Candidates must have experience with *_C#, ASP.net MVC, Web Services and MS Azure cloud...  More
7 days ago

Norwalk, CT 19-July-2016

Sr. Net Developer
Source: Indeed
Details: Net:. Experience with Web Technologies such as ASP.NET Web Forms, ASP.NET MVC, ASP.NET WCF, HTML, Javascript, CSS, JQuery. ExpertASP.NET Development Experience....  More
5 days ago

Washington, DC 21-July-2016

Back-End Web Developer
Source: DNTG Software
Details: Experiences with ASP.NET and MVC in C#, Web API. Develop and maintain secure and stateless web services using Microsoft ASP.NET MVC 4.0 based on the REST...  More
8 days ago

Buena Park, CA 18-July-2016

.Net Developer
Source: TEKSystems
Details: Expert-level expertise with ASP.NET MVC. Experience with MVC 4, design patterns, and modern architectural trends....  More
13 hours ago

Los Angeles, CA 26-July-2016

Web Developer/Programmer
Source: Indeed
Details: MVC:. ASP.Net MVC and C#.Net experience a must; This position could be Full or Part time....  More
11 days ago

Sarasota, FL 34232 15-July-2016

.NET Developer
Source: TEKSystems
Details: Design and develop the UI using MVC. Demonstrated understanding of C#, ASP.NET, MVC and Microsoft SQL Server....  More
1 day ago

Frankfort, KY 25-July-2016

Applications Developer 3 - .NET
Source: Metropolitan Council
Details: Work in an environment that allows you to have a life outside of work and does NOT require travel. Flexible schedules and work from home one day a week are  More
4 days ago

Minneapolis, MN 55432 22-July-2016

MEAN stack, ASP.NET C# MVC/Web API Developer
Source: Indeed
Details: Experience working ASP.NET MVC, Web API. 4-5 years - Strong knowledge of MVC and MVVM design pattern. 4-5 years - Experience building web applications....  More
15 days ago

Jersey City, NJ 07310 11-July-2016

C# .Net Developer
Source: Indeed
Details: *Selman & Company* is a leading provider of administrative services related to life & health insurance and similar products with offices in Cleveland, OH &  More
15 days ago

Cleveland, OH 44124 11-July-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.