In my previous blog, last year I compared WCF and Web API, two powerful frameworks which provide us with a set of useful tools used to expose web services online. I explained how WCF evolved into a super customizable framework which can be used practically on almost every data protocol. However I also mentioned how there was a need to make better use of the commonly used, powerful HTTP protocol in order to create web services which are going to be consumed online by web browsers. I also mentioned the concept of REST services and how these can be implemented by both WCF and the WEB API frameworks. In this blog I decided to show you how we can implement some simple REST services using Web API. The reason why I'm choosing Web API over WCF is because Web API is much simpler to configure and since its built on the elegant routing of the ASP.NET MVC architecture, most of our configuration is already done and the underlying routing is automatically set up for us by the ASP.NET MVC routing engines. 

The Architecture

As we can see on the diagram below, the API controller is built over the ASP.NET Pipeline and ASP.NET Routing. However the WebAPI routing is a little bit different from the MVC Routing. The WebAPI uses the HttpRouteCollection and Route objects. The reason why the routing is a bit different in WebAPI is because the WebAPI team wanted to avoid having the class dependencies of ASP.NET for these web services and therefore it can be hosted in console or as a Windows sevice known as self-hosting. In WebAPI routing the architecture does not only regsiter the HttpRoute object but it will also create a wrapper around it in the routing engine known as the Route.

Content Negotiation

Another essential asset of WebAPI is content negotiation. The ability for the requesting application to request data in the desired format. Content negotiation is the process of selecting the best representation for a given response when there are multiple representations available. By default the WebAPI returns data in JSON or XML formats, however while requesting for a resource we can specify the media type to return so that the webAPI knows what you are requesting and selects the proper formatter to output the data. 

 Implementing a WebAPI solution

 Now we shall see how we can implement a simple WebAPI solution in order to expose a REST method as a service over the HTTP protocol. We're going to create a class which inherits the ApiController class. This informs the .NET framework engine that this controller is not just an MVC controller but a WebAPI controller and its routing should be handled differently. 

The routing of the WebAPI looks slightly different than the MVC routing too as shown in the code snippet below:

    name: "Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }

In this example we're going to create a WebAPI controller which exposes a few HTTP methods. For the sake of simplicty we're going to demostrate only the GET method. In order to create a WebAPI service we need to be able to host it somwhere so that we can test it via a simple browser for instance. In the Nuget Repository there is a WebAPI self hosting application which can help us self host the service locally for testing purposes.

The steps for creating and configuring a WebAPI project are the following

  1. Create a Console Project on Visual Studio
  2. Download the Microsoft.AspNet.WebAPI.SelfHost tool from the Nuget manager
  3. Create a controller which inherits from the ApiController
  4. Implement the 'GET' action which will return a list of products
  5. For Hosting
    1. In program.cs create an instance of HttpSelfHostConfiguration by specifying the URL to listen and set the default route map
    2. Create an instance pf HttpSelfHostServer with the configuration and open the connection to wait for client requests

Those are the 5 simple steps in which one can create a WebAPI service which is already listenting for request. Below is a sample of the code implemented within the GET call:

public class ProductsController : ApiController
    Product[] products = new Product[] 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 

   public List<Product> GetProducts()
        return products.toList();

 The hosting part is included in the Main method as shown below:

static void Main(string[] args)
    var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Press Enter to exit."); Console.ReadLine(); } }

 All that is left now is to make a simple URL call and get the returned results. By calling the following URL in the browser: http://localhost:8080/GetProducts,  the GET API call is invoked and a list of all products is returned. As there was no specific request for the returned content type, the WebAPI returns the list of products in XML format because its being called through a browser:

Well thats all from me for today. In future blogs I plan on showing you more cool stuff we can do with WebAPI and how we can make these requests via JQuery or mobile devices. Until then I hope you have a good week and keep in touch with any ideas or awsome technologies you come across.