Getting started with the ASP.NET Web API

Some time ago I did a number of blog posts about the beta versions of the WCF Web API. As it turns out the WCF Web API team has moved into the ASP.NET team, a good thing as far as I am concerned, and as a result it is now called ASP.NET Web API. Now this is much more that just a name change. For starters there is very little of the WCF bits still involved, in fact when you use ASP.NET as a host none at all. As a result it takes on quite a few characteristics of ASP.NET MVC with convention over configuration. Quite a difference from WCF which is all about taking configuration to the max.

In this blog post I am going to show how to get started with the ASP.NET Web API.


What is the ASP.NET Web API all about?

The ASP.NET Web API is a framework build on top of the core ASP.NET engine for creating REST services. And REST services have become relatively popular as a result of the popularity of web and mobile applications where the traditional SOAP service are a bit to rigid and cumbersome to work with. Now this certainly doesn’t mean that SOAP services are going to disappear but we will see an increasing number of REST services as an addition.

On .NET there are a number of different options for REST services. There are some pretty good open source alternatives like OpenRasta. And the WCF team has made a number of attempts at providing a REST framework in the past which where usable but less successful. The WCF Web API was a big improvement as that was much more inline with HTTP, as a RESTful service should be, but the tie to WCF was a bit a problem as the whole WCF stack was architected and build with SOAP in mind.

The ASP.NET Web API should provide a far more flexible framework for building RESTful services.

The ASP.NET Web API bits ship as part of ASP.NET MVC4 beta right now but that doesn’t mean you are tied to using an MVC application. Personally I like MVC but if you prefer ASP.NET WebForms that will work fine, in fact you can use any ASP.NET as a host. For that matter if you don’t want an ASP.NET host it is perfectly fine to self host the ASP.NET Web API in whatever host application you want. Console, Windows Service you name it and it should just work. But I am going to leave self hosting for another post as I suspect most people will host their Web API as part of an ASP.NET web site. So in this demo I am going to use ASP.NET MVC 4.


Creating a ASP.NET MVC 4 new application

When you create a new MVC 4 application you get the option of creating a Web API project. There is nothing wrong with that but in this case I am not going to do that and I am just going to create a standard Internet Application and add a Web API to that.


I have a copy of the Northwind database on my machine and I am going to create a Web API service to return the products data from that database. So first I need to create a Entity Framework model with the table definition.



Next we need a controller to return the product data. Instead of a normal MVC controller we should be using an ApiController here. An ApiController is a special type of controller all geared towards creating a REST service. The convention is to store these in an API folder. The same convention as with regular MVC applies so we have to create a controller named ProductsController.

The resulting code is quite simple but it shows us how to get started with an ASP.NET Web API controller.

   1: public class ProductsController : ApiController

   2: {

   3:     // GET /api/<controller>

   4:     public IEnumerable<string> Get()

   5:     {

   6:         return new string[] { "value1", "value2" };

   7:     }


   9:     // GET /api/<controller>/5

  10:     public string Get(int id)

  11:     {

  12:         return "value";

  13:     }


  15:     // POST /api/<controller>

  16:     public void Post(string value)

  17:     {

  18:     }


  20:     // PUT /api/<controller>/5

  21:     public void Put(int id, string value)

  22:     {

  23:     }


  25:     // DELETE /api/<controller>/5

  26:     public void Delete(int id)

  27:     {

  28:     }

  29: }

In fact if we run the application as is and navigate to the URL for this controller, in my case http://localhost:3438/api/products but your port number is going to be different, we can see it already returns some data.


So why does this URL work? Well out of the box an ASP.NET MVC4 project has 2 routes configured. One for the normal controller and the other for Web API controllers. You can find the relevant code in the global.asax.

   1: public static void RegisterRoutes(RouteCollection routes)

   2: {

   3:     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


   5:     routes.MapHttpRoute(

   6:         name: "DefaultApi",

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

   8:         defaults: new { id = RouteParameter.Optional }

   9:     );


  11:     routes.MapRoute(

  12:         name: "Default",

  13:         url: "{controller}/{action}/{id}",

  14:         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

  15:     );

  16: }

Of course you are free to change the path but for now I am going to leave it as is as the default convention of putting Web API request in an API URL makes sense to me.


There are a couple of things to note in the code for the ProductsController. First of all there are no attributes used. WCF was all about attributes, MVC is all about conventions. So the the convention is if the function name starts with Get it will respond to an HTTP GET method, if it starts with Post it responds to an HTTP POST method and so on. You can change this with attributed but it sounds perfectly fine and good enough for me. What matters is the start of the function name. So changing it to GetProducts() will work just fine but using LoadProducts() will result in the following error:

The parameters dictionary contains a null entry for parameter ‘id’ of non-nullable type ‘System.Int32’ for method ‘System.String Get(Int32)’ in ‘WebAPIDemo.Api.Controllers.ProductsController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Not quite a clear an error message as I would have liked Sad smile But then it is only a beta so there is hope.

Returning some actual product data from our Web API service

Doing that is actually quite easy. All we need to do is redefine the Get() function to return an IEnumerable<Product>, instantiate a NorthwindEntities context and return the Products collection.

   1: public class ProductsController : ApiController

   2: {

   3:     private NorthwindEntities _db = new NorthwindEntities();


   5:     // GET /api/<controller>

   6:     public IEnumerable<Product> Get()

   7:     {

   8:         return _db.Products.ToList();

   9:     }


  11:     protected override void Dispose(bool disposing)

  12:     {

  13:         if (disposing && _db != null)

  14:         {

  15:             _db.Dispose();

  16:             _db = null;

  17:         }

  18:         base.Dispose(disposing);

  19:     }

  20: }

Refreshing the page in the browser now returns the products data as expected:


Returning the a single product is just as easy. Just implement the Get(int id) function to return the correct Product as follows.

   1: // GET /api/<controller>/5

   2: public Product Get(int id)

   3: {

   4:     return _db.Products.Single(p => p.ProductID == id);

   5: }


Not surprisingly just the single product is returned when we add a product id to the URL.


That is enough for a first post. Next time I am going to take a look at what it takes to add new or update existing product data using the ASP.NET Web API.






One thought on “Getting started with the ASP.NET Web API

Leave a Reply

Your email address will not be published. Required fields are marked *