First look at the ASP.NET Web API | John V. Petersen


: 6

All of the code for this post can be downloaded here.

Sorry for the bad link. You can find the code here.

If you have not heard already, ASP.NET MVC 4 has reached the beta stage. You can download the bits here.  There are lots of new goodies in this release – which I’ve already discussed in the latest issue of  Code Magazine. The one item  I want to discuss now is the addition of ASP.NET Web API. If you have been looking for a way to build RESTful services in ASP, the ASP.NET Web API library is something you are going to want to look at.  REST is an architecture – and it is not new. The entire web is an example of REST at work. In REST, there are 4 primary verbs that we are concerned with:

  • POST: Create a new entity
  • PUT: Update an existing entity
  • GET: Retrieve a specified entity
  • DELETE: Delete a specified entity

One of the characteristics of an MVC style app is it’s support for RESTful style URL’s. For example:

The intent of of this domain is clear – we are invoking the edit action of the products controller – passing the id 1 as a parameter. This is an example of a GET operation. The result is a view rendered to the browser that contains a combination of html markup, css styles and data.

To update data, a URL like this may apply:

Similar to the previous example, except that this would a POST operation because data is being updated. In other words, some side-effect is going to result from this operation.  The controller action in this case would be named edit and would be decorated with the [HttpPost] attribute. The body of the web request would contain the data that is sent (posted) back to the server. The parameter in this case would be an instance of a product class. The process of turning that raw data into an object we would with in C# or VB is handled by ASP.NET’s model binding service.

In MVC, those are the two verbs we typically work with: POST and GET. And for the most part, that’s all you really need. But what if you need something that is a bit more generic and relies on the intrinsics of the http protocol? This is where the Web API comes in and as you will see,  it’s really simple to use.

Getting Started

Once you have downloaded and installed the MVC 4 Beta, start Visual Studio and choose to create a new ASP.NET MVC 4 application. Right away, you will see more project choices. The template we will work with is the Web API template.


On the ASP.NET MVC site, there is already a tutorial on building your first Web API Project. The example starts with that project and then extends to cover more aspects of the Web API.

One of the first things I did was add a test project:


The second thing I did was to remove the code in the Products Controller. All of the data-related code was refactored to a Products Repository class.

One of the first things you may notice is that only 1 of the controller actions is decorated with an http verb. This is where convention over configuration comes into play. By default, if you prefix the name of  your API actions with with the verb it responds to, you are done! Of course, there are cases when you will want to name your API actions in a different way. You can do that as well. All you need to do is specify the correct verb attribute.

For this example, I ended up ripping out a lot of the MVC artifacts that don’t apply in a Web API context.  Nevertheless, System.Web.MVC is still required as among many things, the MVC routing engine is used.  The route is specified in the Global.asax file – just like any ASP.NET MVC application.

Once you fire up the server, you can begin to interact with the API. For the get operations, you can use a browser. However, if you are doing this sort of work, you need to work with something like Fiddler since you will also need to invoke the POST, PUT and DELETE verbs as well.

http://localhost:18950/api/products :


Once the execute button is clicked, here are the results:


By default, JSON is returned. With a simple change to the content type, which we can easily do in Fiddler, we can get XML back:



What if we want to create a new product? In that case, we would invoke the POST method. We also need to provide the data for the new product:


Now, when we issue a get (with no parameters meaning we are returning all products) – we get the following:


To delete the product we just created? – All we need to do is invoke the DELETE method and specify the id in the URL of the product we wish to delete:


The Web API can easily be equipped with the ability to throw exceptions when a specified product ID cannot be found. In HTTP parlance, this would be translate into a 404. On the other hand, if you attempt to  create a duplicate product, a 500 server error might result.  The overarching point is that our API is very generic – relying on the http protocol to do the heavy lifting.

Another thing you may have noticed is that the routing just works. I’ve said many times, there are only 4 things we can do with data:

  • Create
  • Retrieve
  • Update
  • Delete

These are the CRUD operations. No matter how complex our applications, at a fundamental level, every operation falls into one of these categories. And as you can tell, each of these CRUD operations maps to the 4 operations discussed here. When we create, we post, retrievals are gets, updates are puts and deletes are deletes.

In this example, the Web API is a facade for our data/business layer – which in this case, is expressed as a simple repository. That repository can be used anywhere. The Web API is just another client to those services. The Web API is also a service – a RESTful service as it happens to be – just waiting to respond to requests.

Fiddler is fine as an interactive tool. But what about support for automated tests? Included in the example is a complete test project. To illustrate, review the tests in the test project

public void TestGetProductJSON()
 var expected = "{\"Id\":1,\"Name\":\"Gizmo 1\",\"Price\":1.99}";

 var response = this.getRequest("GET", "application/json", "http://localhost:18950/api/products/1").GetResponse();
 var actual = this.unPackResponse(response);

 Assert.AreEqual(expected, actual);

I’ve created a few helper methods to DRY-up the tests.

I’ve included tests that illustrate both JSON and XML output. I’ve also covered all of the actions (GET, PUT, POST and DELETE).


I look forward to working with and learning more about the ASP.NET Web API. I think this is a great addition to ASP stack and on future projects, I will use the ASP.NET Web API project type to expose the data my ASP.NET MVC project will interact with. To some degree, we could already do this sort of thing with MVC since it is rather easy to return JSON and XML. BUT – some of that didn’t come for free. The ASP.NET Web API is a preferable alternative.