ASP.Net Web API

Posted: October 14, 2013 in Uncategorized

What is ASP.Net WebAPI

In this article, I will take you through the basics of ASP.Net Web API. Restful Service is a buzz word now a days. Since, we want Services to be platform agnostic and support all types of devices , Http based services were introduced. WebAPI is just a step forward in this direction. 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 WebAPI.

Some of the salient features of WebAPI are :

  • Modern HTTP programming model: It uses the power of Http as Http is simple, ubiquitous and flexible.
  • Routing support : Supports routing capabilities similar to 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 which typically support JSON, XML , 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.

Lets get started with a sample for creating a WebAPI Service.

 1. Create a new MVC4 Application as seen below :

Image

 2. Select the Project Type as WebAPI.

 

Image

 

  3. This will create a MCV4 Application with WebAPI infrastructure and a sample Service already available.

  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 WebAPI

If you go to WebAPIConfig class, 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 “controller/action/parameters” format where WebAPI Urls are “api/controller/parameters”.

5. 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 method is different, we can also use Attributes to indicate Verbs. Copy and paste below StudentController class. Please note that the class  should be placed under Controller folder as seen below:

 Image

 

  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 VS.Net 2012 environment.

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

 Image

 

 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. Lets us test all the Http Verbs one by one.

 10. On the fiddler , paste url as  <help-page url>/api/Student/Get

 Image

 

Select Verb as Get(in the first dropdown) and click on Execute button.

 

 

 

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

 Image

On the fiddler, output will be as seen below :

 Image

 

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

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

 Image

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

 

 Image

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

 

 

You can run through the sample and test all operations.

 

WebAPI is currently embraced as it is more lightweight and suited for all devices and it also relies purely on Http programming model. Content negotiation, Rest support and routing are also important features for WebAPI. I will try to come up with series of articles and take this discussion forward.

 

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

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s