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“.
Exam: 70-487
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

C# Developer
Source: Posh Technologies
Details: 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript. 10+ years of Software development experience with strong background in computer...  More
9 days ago

Redmond, WA 22-May-2016

C# Developer
Source: Diverse Lynx
Details: ASP.NET MVC, AngularJS. We need a strong developer having following skills:....  More
11 days ago

Redmond, WA 20-May-2016

ASP.NET MVC Front-End Developer
Source: Webtellect, LLC
Details: 3+ years of ASP.NET MVC development. Proven past experience of the ASP.NET MVC stack. The team member needs to be adept and skilled in HTML, CSS, and Javascript...  More
22 days ago

Redmond, WA 09-May-2016

Sr. Applications Developer
Source: Ruan
Details: Experience using the Microsoft stack with extensive knowledge in C#, SQL Server and ASP.NET MVC. Sr....  More
27 days ago

Des Moines, IA 03-May-2016

ASP.NET MVC Developer
Source: Noblis
Details: Twitter Bootstrap JavaScript MVC Framework e.g. AngularJS, KnockoutJS Web API SharePoint (Content Management) Oracle (PL-SQL) Azure Cloud APIs Mobile...  More
30+ days ago

Falls Church, VA 22042 20-April-2016

Senior .Net Developer
Source: Indeed
Details: (ASP.Net MVC, C#, Entity Framework, SQL Server 2012 etc.). Bachelor’s Degree required, Master’s Degree strongly preferred....  More
6 hours ago

Dallas, TX 31-May-2016

.NET Developer
Source: Graphic Products
Details: ASP.Net MVC Framework. Graphic Products is seeking a .NET Web Developer to join our IT department....  More
5 days ago

Beaverton, OR 97008 26-May-2016

Junior C#/ASP.Net/MVC Developer - 3 months+ (Fairfield, NJ)
Source: Indeed
Details: Experience with MVC, Xamarin, Telerik, SSIS is a plus. Junior C#/ASP.Net Developer - 3 months+ Contract*....  More
30+ days ago

Fairfield, NJ 28-April-2016

.NET Web Developer
Source: Indeed
Details: ASP.Net MVC Framework. Graphic Products is seeking a .NET Web Developer to join our IT department....  More
5 days ago

Beaverton, OR 97008 26-May-2016

Web Developer-ASP.NET/ MVC/SQL Server Developer
Source: Cigna
Details: Experience with MVC design patterns is required. Strong understanding of web design as it relates to MVC design patterns, attuned to the fundamentals of user...  More
19 days ago

Bloomfield, CT 12-May-2016

Senior .Net Web Developer
Source: Indeed
Details: *SENIOR .NET WEB DEVELOPER* *Job Description* We are looking for an experienced web developer to join the development team. The Senior Web Developer will be  More
5 days ago

Basking Ridge, NJ 26-May-2016

Software Developer
Source: Indeed
Details: .NET platform – including C#, ASP.NET, MVC, Web API, and Entity Framework. This is made up of a number of systems ranging from front-end websites to backend...  More
26 days ago

Seattle, WA 05-May-2016

Junior .NET WEB DEVELOPER
Source: Indeed
Details: C#, ASP.NET, MVC, Web API, XML, JSON, MySQL, HTML5, CSS3, JavaScript, jQuery, AJAX, Bootstrap:. Experience developing enterprise-class web-based software using...  More
30+ days ago

Solon, OH 27-April-2016

Full Stack Developer (FT); Trevose/Bensalem, PA area
Source: Indeed
Details: Expertise in MS technologies, including .NET 4.0/4.5, C#, ASP.Net MVC, WebApi, IIS, SQL Server, etc.:. Expert knowledge of Microsoft technologies, including...  More
7 days ago

Feasterville-Trevose, PA 19053 24-May-2016

c# .net Developer
Source: Diverse Lynx
Details: ASP.NET MVC, AngularJS. Strong developer having following skills:....  More
19 days ago

Redmond, WA 12-May-2016

.NET Developer
Source: Indeed
Details: Visual Studio 2013+ • .NET 4.5+ • ASP.NET MVC 4+ • Web App (GUI building experience) • HTML5 • C# • NuGet • log4net • TFS SQL Server 2014+ • SQL (not necessary...  More
7 days ago

Chicago, IL 24-May-2016

Senior .Net Developer / Architect
Source: Indeed
Details: Expert in Microsoft tools and technologies, particularly .NET/C#, MVC. .NET SQL C# Software Development Agile Methodologies SDLC T-SQL ASP.NET Applications...  More
8 days ago

Nashville, TN 23-May-2016

.Net Developer
Source: Indeed
Details: IT, Information Technology, .Net web developer, .Net Developer, Software, Software Engineer, .Net, full development stack, HTML, HTML 5, CSS, JavaScript, Java,...  More
30+ days ago

Reston, VA 02-March-2016

Junior software developer
Source: Indeed
Details: Preferred Experience with ASP .NET MVC. ASP.NET MVC, Microsoft SQL Server, Bootstrap:. Open career opportunity for an entry level programmer....  More
10 days ago

Flowood, MS 21-May-2016

.NET Developer
Source: CGI
Details: •Solid understanding of UI Framework especially with MVC. •Experience with Razor View Engine and ASP.net MVC framework....  More
30+ days ago

Columbus, OH 43240 26-April-2016

.NET Developer
Source: Indeed
Details: MVC,. Experienced in developing ASP.NET MVC 3+ Web applications,. NY, Edgewood, Long Island....  More
11 days ago

Long Island, NY 19-May-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
1 day ago

Dallas, TX 30-May-2016

Front End/UI Developer
Source: Indeed
Details: 3+ years web development experience- ASP.NET MVC, Ruby, or similar. .net, mvc, web application, javascript, html, css, sql, linq, jquery, ajax, c#, asp.net,...  More
14 days ago

Arlington, VA 17-May-2016

Senior Developer/Designer with.NET and Azure Experience, Houston TX
Source: CSC
Details: Requirements Must have strong C# skills with hands-on experiences with object oriented programming Understanding of SOA including Web API ASP.NET MVC OData...  More
2 days ago

Houston, TX 77056 29-May-2016

.Net Developer
Source: Indeed
Details: Position: .net developer Location: Georgetown DC Duration: 6 month contract to hire 120,000 conversion salary Top Three skill sets: * ASP.net/MVC * AngularJs   More
28 days ago

Alexandria, VA 03-May-2016
Category: ASP.NET Web API ASP.NET Web Forms

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.