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.

protected void Application_Start()

{

    AreaRegistration.RegisterAllAreas(); 

    WebApiConfig.Register(GlobalConfiguration.Configuration);

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    BundleConfig.RegisterBundles(BundleTable.Bundles);

}

The highlighted line shows the routing configuration for the WebAPI.

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

public static class WebApiConfig

{

    public static void Register(HttpConfiguration config)

    {

        config.Routes.MapHttpRoute(

                 name: "DefaultApi",

        routeTemplate: "api/{controller}/{id}",

        defaults: new { id = RouteParameter.Optional }

        );

    }

}

 
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
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

 

namespace SampleWebAPI.Controllers

{

    public class StudentController : ApiController

    {

        static List<Student> StudentList = InitStudents();

 

        private static List<Student> InitStudents()

        {

            List<Student> tempList = new List<Student>();

            tempList.Add(new Student() { ID = 1, Name = "A" });

            tempList.Add(new Student() { ID = 2, Name = "B" });

            return tempList;

        }

        // GET api/student

        [HttpGet]

        public IEnumerable<Student> FetchStudents()

        {

            return StudentList;

        }

        // POST api/student

        public Student Post(Student student)

        {

            StudentList.Add(student);

            return student;

        }

        // PUT api/student/5

        public Student Put(int id, string name)

        {

            var tempstudent = StudentList.Where(p => p.ID == id).SingleOrDefault();

 

            if (tempstudent != null)

            {

                tempstudent.Name = name;

            }

 

            return tempstudent;

        }

 

        // DELETE api/values/5

        public void Delete(int id)

        {

            var student = StudentList.Where(p => p.ID == id).SingleOrDefault();

 

            if (student != null)

            {

                StudentList.Remove(student);

            }

        }

    }

 

    public class Student

    {

        public int ID { get; set; }

        public string Name { get; set; }

    }

}

 

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.

Up Next
    Ebook Download
    View all
    Learn
    View all