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

Senior Software Developer
Source: BitTitan
Details: Working with technologies across the Microsoft stack including ASP.NET MVC, LINQ and SQL Server. Who is BitTitan?...  More
24 days ago

Kirkland, WA 02-September-2016

Senior Software Developer
Source: Indeed
Details: The Senior Software Developer must have knowledge of Microsoft technologies, including Microsoft .NET 4.0/4.5, C#, ASP.NET MVC, WebApi, IIS, Entity Framework,...  More
13 days ago

Chesapeake, VA 13-September-2016

Senior Software Developer
Source: Crest Financial
Details: ASP, .NET, MVC. Crest Financial, the fastest growing leasing company in Utah, is growing and looking to hire a new Senior Software Developer....  More
17 days ago

Draper, UT 09-September-2016

Senior Developer
Source: Inuvo, Inc
Details: Experience building and running large scale production web applications using ASP.NET MVC and Web API. Inuvo is looking to hire talented engineers to join a...  More
11 days ago

Little Rock, AR 72201 15-September-2016

C# Developer
Source: Inuvo, Inc
Details: Experience with Agile methodologies, building and running large scale production web applications using ASP.NET MVC and Web API....  More
11 days ago

Little Rock, AR 72201 15-September-2016

Full Stack Developer
Source: Indeed
Details: Develop UI components using technologies such as ASP.NET MVC, JavaScript, React.js, JQuery. 5+ years of experience using web technologies including ASP.NET MVC,...  More
3 days ago

Philadelphia, PA 23-September-2016

Application Developer (Secret Clearance)
Source: Indeed
Details: *Overview* Are you looking for an opportunity to join a growing company that is innovative, cutting edge, and mission centered? Our prestigious technical and  More
2 days ago

Arlington, VA 25-September-2016

Application Developer
Source: Indeed
Details: 3+ years of development experience using Microsoft IIS, C#, ASP.NET, MVC, VB, NET, XML and SQL Server. Jefferson Capital Systems, LLC is an industry-leading...  More
5 days ago

Saint Cloud, MN 56303 21-September-2016

Application Developer
Source: Indeed
Details: ASP.NET, ASP.NET MVC, MS SQL Server, HTML, CSS, JavaScript, C#/VB.NET and Microsoft development stac:. Minimum 3 years’ experience with established development...  More
5 days ago

Miami, FL 21-September-2016

Application Developer
Source: Indeed
Details: Working knowledge of C#, ASP.NET, MVC, and Visual Studio. We have an opening for a dynamic Application Developer who is passionate about what they do and...  More
7 days ago

Cranston, RI 19-September-2016

Application Developer
Source: Indeed
Details: HTTP, AJAX, HTML5, ASP.NET WebForms, ASP.NET MVC, MVVM, JavaScript/jQuery and CSS3. Long term consulting assignment over two years....  More
12 days ago

Phoenix, AZ 15-September-2016

Mobile Application Developer
Source: Indeed
Details: HTTP, AJAX, HTML5, ASP.NET WebForms, ASP.NET MVC, MVVM, JavaScript/jQuery and CSS3. Mobile Application Developer....  More
12 days ago

Phoenix, AZ 14-September-2016

Software Developer
Source: Indeed
Details: ASP.NET MVC experience is required. Build and maintain application functionality for new and existing systems.Participate in all aspects of the software...  More
18 days ago

Rancho Cordova, CA 08-September-2016

Software Developer
Source: Indeed
Details: C#, SQL, HTML, CSS, JSON, JavaScript, ASP.NET Web Forms, ASP.NET MVC, Visual Studio. Does this describe you?*....  More
3 days ago

Miamisburg, OH 45342 23-September-2016

Software Developer (Early Career)
Source: Indeed
Details: Working knowledge of WinForms, MVC, and entity framework. Web Programming experience with JavaScript, Ajax, JQuery, HTML, ASP.NET, MVC, responsive design....  More
4 days ago

Fargo, ND 58104 22-September-2016

Software Developer Internship
Source: Arbiter Sports
Details: 0-1 year software development experience or academic exposure in developing web applications using ASP.NET MVC, C#, SQL Server and Entity Framework....  More
5 days ago

Sandy, UT 84070 21-September-2016

Programmer IV
Source: Indeed
Details: MVC Entity Framework. Reviews, analyzes, and modifies programming systems including encoding, testing, debugging and documenting programs....  More
17 hours ago

Salem, OR 26-September-2016

Software Developer w/experience
Source: Indeed
Details: 1 year ASP.net MVC experience preferred. Some experience developing Web applications using ASP.net MVC. Develop custom applications in Visual Studio’s VB.Net/C#...  More
7 days ago

Louisville, KY 19-September-2016

Junior Developer/Tier II Support
Source: OutMatch
Details: Develop and enhance Web-based and Mobile Web SaaS applications using Microsoft technologies, ASP.NET, ASP.NET MVC, JS libraries and MS SQL Server Databases....  More
13 days ago

Dallas, TX 75251 13-September-2016

C# Developer
Source: CareWorks Tech
Details: ASP.Net, ASP.Net MVC. Proven track record of hands-on technical design and code work within large complex systems....  More
30+ days ago

Columbus, OH 15-August-2016

.Net Developer(Front end Technologies)
Source: Indeed
Details: Projects range widely from SharePoint applications (including Visual Web Parts), to Windows services, to full-stack ASP.NET MVC applications....  More
6 days ago

Redmond, WA 20-September-2016

Software Developer
Source: Indeed
Details: The Software Developer must have knowledge of Microsoft technologies, including Microsoft .NET 4.0/4.5, C#, ASP.NET MVC, WebApi, IIS, Entity Framework, SQL...  More
13 days ago

Chesapeake, VA 13-September-2016

Software Developer Intern
Source: Health Catalyst
Details: Job Title: SoftwareDeveloper/Test Intern Department: Product Development Classification: Intern Status: Full-time (40 hours/week) Location: Salt Lake City  More
14 days ago

Salt Lake City, UT 12-September-2016

Junior Software Developer
Source: Indeed
Details: Net MVC, C#, VB.Net, SQL Server, Visual Studio, and Web Services. Junior Software Developer*....  More
18 days ago

Irving, TX 08-September-2016

Software Developer
Source: NuGrowth Solutions
Details: The ideal candidate will be fluent in C#, ASP.NET MVC, SQL Server and Web Service Architecture. SIS, a leading provider of Agency Management Systems for...  More
16 days ago

Columbus, OH 43228 10-September-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.