Creating simple Web API using the new MVC 4
As a follow up on the previous blog, one of the immediate features of the new MVC 4 beta is the ability to create Web API.
HTTP is not just for serving up web pages. It is also a powerful platform for building services. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
ASP.NET Web API is a framework for building HTTP services on top of the .NET Framework. In this tutorial, you will create your first HTTP service using ASP.NET Web API. The service itself will be trivial, but it will give you a quick introduction of ASP.NET Web API. After that, you can follow some of the more detailed tutorials and samples.
Here’s how to create a new web API
Start Visual Studio 2010 and select New Project from the Start page. Or, from the File menu, select New and then Project.
In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project “HelloWebAPI” and click OK.

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

Adding a Model
A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.
To see all of this in action, let’s start by creating a simple model.
If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context meny, select Add then select Class.

Name the class “Product”. Next, add the following properties to the Product class.
namespace HelloWebAPI.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Adding a Controller
A controller is an object that handles HTTP requests from the client. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.
- HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to our Web API service. ValuesController is an example WebAPI controller.
Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
Let’s rename ValuesController. In Solution Explorer, right-click ValuesController.cs and select Rename.

Rename the file “ProductsController.cs”.

When you type Enter, Visual Studio will prompt you whether to rename all references to the code element “ValuesController”:

Click Yes. This will cause Visual Studio to rename the class definition along with the file name:
namespace HelloWebAPI.Controllers
{
public class ProductsController : ApiController
{
// Methods not shown...
}
}
Add the following using statement to ProductsController.cs:
using HelloWebAPI.Models;
Delete the existing methods from the ProductsController class. Then add the following two methods:
public IEnumerable<Product> GetAllProducts()
{
return new List<Product>
{
new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }
};
}
public Product GetProductById(int id)
{
if (id < 1 || id > 3)
{
throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
}
return new Product() { Id = id, Name = "Gizmo " + id.ToString(), Price = id + 0.99M };
}
The GetAllProducts method returns a list of products, as an IEnumerable<Product> type. The GetProductById method returns a product specified by ID value. For this tutorial, we want to keep the code as simple as possible, so both methods return hard-coded values. In the case of GetProductById, we set the product name to “Gizmo id“. For example, if the user requests ID = 2, the method returns “Gizmo 2″. Notice that GetProductId throws an exception of type HttpResponseException if id is not valid. This exception will be translated by the framework into a 404 (Not Found) error.
That’s it! You have a working HTTP service. Now let’s write a client to access the service.
Calling the HTTP Service with JSCript or JQuery
In Solution Explorer, expand the Views folder, and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Index.cshtml renders HTML using the Razor view engine. However, we will not use any Razor features in this tutorial, because I want to show how a client can access the service using plain HTML and Javascript. Therefore, go ahead and delete everything in this file, and replace it with the following:
<!DOCTYPE html> <html lang="en"> <head> <title>ASP.NET Web API</title> <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> </head> <body> <div> <h1>All Products</h1> <ul id='products' /> </div> <div> <label for="prodId">ID:</label> <input type="text" id="prodId" size="5"/> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> </body> </html>
Getting a List of Products
To get a list of products, send an HTTP GET request to “/api/products”. You can do this with jQuery as follows:
<script type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/products/",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.Price;
// Add a list item for the product.
$('<li/>', { html: str })
.appendTo($('#products'));
});
});
});
</script>
The getJSON function sends the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.
Getting a Product By ID
To get a product by ID, send an HTTP GET request to “/api/products/id“, where id is the product ID. Add the following code to the script block:
function find() {
var id = $('#prodId').val();
$.getJSON("api/products/" + id,
function (data) {
var str = data.Name + ': $' + data.Price;
$('#product').html(str);
})
.fail(
function (jqXHR, textStatus, err) {
$('#product').html('Error: ' + err);
});
}
Again, we call the jQuery getJSON function to send the AJAX request, but this time we use the ID to construct the request URI. The response from this request is a JSON representation of a single Product object.
The following code shows the complete Index.cshtml file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>ASP.NET Web API</title>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/products/",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.Price;
// Add a list item for the product.
$('<li/>', { html: str }).appendTo($('#products'));
});
});
});
function find() {
var id = $('#prodId').val();
$.getJSON("api/products/" + id,
function (data) {
var str = data.Name + ': $' + data.Price;
$('#product').html(str);
})
.fail(
function (jqXHR, textStatus, err) {
$('#product').html('Error: ' + err);
});
}
</script>
</head>
<body>
<div>
<h1>All Products</h1>
<ul id='products' />
</div>
<div>
<label for="prodId">ID:</label>
<input type="text" id="prodId" size="5"/>
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
</body>
</html>
Now time to Run the app
Press F5 to start debugging the application. Visual Studio will build the project and start the ASP.NET Development Server. By default, Visual Studio assigns a random port to the development server. Visual Studio will then automatically open a browser window that points to http://localhost:xxxx/, where xxxx is the randomly assigned port number. The web page should look like the following:

It’s not flashy, but it shows that our HTTP service is working. You can get a product by ID by entering the ID in the text box:

If you enter an invalid ID, the server returns an HTTP error:

Understanding Routing
For each HTTP message, the ASP.NET Web API framework decides which controller receives the request by consulting a table. We’ll discuss routing in more detail in another tutorial, but here is a quick overview. When you create a new Web API project, the project contains a default route that looks like this:
/api/{controller}/{id}
The {controller} and {id} portions are placeholders. When the framework sees a URI that matches this pattern, it looks for a controller method to invoke, as follows:
- {controller} is matched to the controller name.
- The HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.)
- {id}, if present, is matched to a method parameter named id.
Here are some example requests, and the action that results from each, given our current implementation.
| HTTP Method | URI | Action |
|---|---|---|
| GET | /api/products | GetAllProducts() |
| GET | /api/products/5 | GetProduct(5) |
| POST | /api/products/ | HTTP Status 405 |
| GET | /api/users/ | HTTP Status 404 |
In the first example, “products” matches the controller named ProductsController. The request is a GET request, so the framework looks for a method on ProductsController whose name starts with “Get…”. Furthermore, the URI does not contain the optional {id} segment, so the framework looks for a method with no parameters. The ProductsController::GetAllProducts method meets all of these requirements.
The second example is the same, except that the URI contains the {id} portion. Therefore, the frameworks calls GetProduct, which takes a parameter named id. Also, notice that value “5″ from the URI is passed in as the value of the id parameter. The framework automatically converts the “5″ to an int type, based on the method signature.
In the third example, the client sends an HTTP POST request. The framework looks for a method whose name starts with “Post…” However, no such method exists in ProductsController, so the framework returns an HTTP response with status 405, Method Not Allowed.
In the fourth example, the client sends a GET request to /api/users. The framework looks for a controller named UsersController. We did not define a controller with that name, so the frameworks returns status 404, Not Found.
Using F12 to see HTTP request and response
When you are working with an HTTP service, it can be very useful to see the HTTP request and request messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:

Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested “application/json” in the Accept header.

If you click the Response body tab, you can see how the product list was serialized to JSON:
[{"Id":1,"Name":"Gizmo 1","Price":1.99},
{"Id":2,"Name":"Gizmo 2","Price":2.99},
{"Id":3,"Name":"Gizmo 3","Price":3.99}]

