What is ASP.Net WebAPI

In this article, I will take you through the basics of the ASP.Net Web API. Restful Service is a buzz word now a days. Since we want services to be platform-independent and support all types of devices, HTTP based services were introduced. WebAPI is just a step forward in this direction. The WebAPI is a framework for building HTTP based services and clients built on top of ASP.Net. REST based services can easily be built on top of the WebAPI.

Some of the salient features of the WebAPI are:

  • Modern HTTP programming model: It uses the power of HTTP since HTTP is simple, ubiquitous and flexible.
  • Routing support: Supports routing capabilities similar to the MVC Framework.
  • Content negotiation: This is one of the major features. The client and server can work together to determine the right format for data being returned from an API. The support is mainly extended in the form of Media formatters that typically support JSON, XML and URL Encoded formats.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request (header, querystring and body) and convert those message parts into .NET objects.
  • Support for filters and OData using IQueryable<T>
  • Support for Self Hosting: Can be hosted using IIS, Exe (Console Application) or as a Windows Service.

Let's get started with a sample for creating a WebAPI Service.

1. Create a new MVC4 Application as seen below.

MVC4 Application

2. Select the Project Type as WebAPI.

Select the Project

3. This will create a MCV4 Application with WebAPI infrastructure and a sample service is already provided.

4. Open Global.asax.cs.

  1. protected void Application_Start()  
  2. {  
  3.     AreaRegistration.RegisterAllAreas();   
  4.     WebApiConfig.Register(GlobalConfiguration.Configuration);  
  5.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  6.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
  7.     BundleConfig.RegisterBundles(BundleTable.Bundles);  
  8. }   

The highlighted line shows the routing configuration for the WebAPI.

If you go to the WebAPIConfig class then you will find:

  1. public static class WebApiConfig  
  2. {  
  3.     public static void Register(HttpConfiguration config)  
  4.     {  
  5.         config.Routes.MapHttpRoute(  
  6.                  name: "DefaultApi",  
  7.         routeTemplate: "api/{controller}/{id}",  
  8.         defaults: new { id = RouteParameter.Optional }  
  9.         );  
  10.     }  
  11. } 

MVC URLs are generally in the "controller/action/parameters" format where WebAPI URLs are "api/controller/parameters".

5. The WebAPI supports all 4 HTTP Verbs namely Get, Post, Put and Delete. As per WebAPI convention, the method names will be mapped to HTTP verbs if the method name starts with Verb. If the method is different then we can also use Attributes to indicate Verbs. Copy and paste the following StudentController class. Please note that the class should be placed under the Controller folder as seen below:

Controller folder

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. namespace SampleWebAPI.Controllers  
  8. {  
  9.     public class StudentController : ApiController  
  10.     {  
  11.         static List<Student> StudentList = InitStudents();  
  12.         private static List<Student> InitStudents()  
  13.         {  
  14.             List<Student> tempList = new List<Student>();  
  15.             tempList.Add(new Student() { ID = 1, Name = "A" });  
  16.             tempList.Add(new Student() { ID = 2, Name = "B" });  
  17.             return tempList;  
  18.         }  
  19.         // GET api/student  
  20.         [HttpGet]  
  21.         public IEnumerable<Student> FetchStudents()  
  22.         {  
  23.             return StudentList;  
  24.         }  
  25.         // POST api/student  
  26.         public Student Post(Student student)  
  27.         {  
  28.             StudentList.Add(student);  
  29.             return student;  
  30.         }  
  31.         // PUT api/student/5  
  32.         public Student Put(int id, string name)  
  33.         {  
  34.             var tempstudent = StudentList.Where(p => p.ID == id).SingleOrDefault();  
  35.             if (tempstudent != null)  
  36.             {  
  37.                 tempstudent.Name = name;  
  38.             }  
  39.             return tempstudent;  
  40.         }  
  41.         // DELETE api/values/5  
  42.         public void Delete(int id)  
  43.         {  
  44.             var student = StudentList.Where(p => p.ID == id).SingleOrDefault();  
  45.             if (student != null)  
  46.             {  
  47.                 StudentList.Remove(student);  
  48.             }  
  49.         }  
  50.     }  
  51.     public class Student  
  52.     {  
  53.         public int ID { getset; }  
  54.         public string Name { getset; }  
  55.     }  
  56. }  

6. Build the solution. I have used the Visual Studio 2012 environment.

7. Just run the application, you should see the ASP.NET Web API help page.

ASP.NET Web API help page

8. To test the WebAPI we will use Fiddler as our client tool. Just open the Fiddler tool (a web debugging tool).

9. Grab the URL from the help page and paste it on the Composer tab of Fiddler. Let's test all the HTTP Verbs one by one.

10. Put a breakpoint inside all methods inside the StudentController.

11. In Fiddler, paste the URL as <help-page url>/api/Student/Get.

Composer tab
Select the Verb "Get" (in the first dropdown) and click on the "Execute" button.

Execute

You can also break at any point inside the code by using breakpoints.

In Fiddler, the output will be as in the following:

output

You can see the list of students displayed in JSON format.

12. Screens for Post operation. Note the use of the Content-Type header and also we are passing values through the Request body. This will insert a new student.

Post operation

13. Follow this up with another Get operation and you will see the new record added.

Get operation

14. In a similar fashion, you can update existing Students using a Put operation and remove an existing Student using a Delete operation.

I have also attached the code for the current sample. You can run through the sample and test all operations.

The WebAPI is currently embraced since it is more lightweight and suited for all devices and it also relies purely on the HTTP programming model. Content negotiation, REST support and routing are also important features for the WebAPI. I will try to write a series of articles continuing with this explanation.

Feel free to leave your comments. Until we meet again, happy coding.


Similar Articles