Announcement:
WCF Web API is now ASP.NET Web API!
ASP.NET Web API released with ASP.NET MVC 4 Beta. The WCF Web API and WCF support for jQuery content on this site wll removed by the end of 2012.
Getting Started: Building a simple Web API
Learning objectives
In this quick start you will learn the basics of how you use WCF Web API with ASP.NET MVC 3*
- How to add Web API to an existing project using NuGet
- How to create a new Web API which can be access through an HTTP GET
- How to host a Web API through ASP.NET routes
- How to query a Web API via the browser or using the Web API test client
- How to enable support for the OData URI queries with your APIs.
*Note: Web API does not requires ASP.NET MVC - it supports multiple hosting configurations including self-host, IIS and ASP.NET (both MVC and Web Forms). This quick start however shows how to host in ASP.NET MVC 3.
Pre-requisites
- Visual Studio 2010 / Visual Studio 2010 SP1
- ASP.NET MVC 3
Code
You can download the solution for this workshop
here.
Scenario
For this quick start the scenario will be building a simple Web API for managing contacts. The application will be consumed by one or more clients and will allow both retrieval of existing contacts as well as creation of new contacts.
1 – Creating the basic solution
- Launch Visual Studio 2010
- File->New Project->ASP.NET MVC 3 Web Application
- Choose ContactManager as the name and specify the location, press “OK”

- Choose “Empty” and click “OK”. An a new ASP.NET MVC 3 solution will be created.
- Right click on the project and choose “Properties”. When the dialog pops up go to the “Web” option.
- Go to the “Servers” section and choose “Specific port” specifying 9000 as the port.
2 – Adding Web API to the solution
The next step will be to use NuGet to bring in the Web API binaries.
- Right click on the project and select “Manage NuGet Packages”

- The “Manage NuGet Packages” dialog will show. Select the “Online” option on the left. Then go to the search box and type “webapi.all”

- Click the “Install” button. NuGet will go and download all of the necessary packages.
- You will notice several Web API references will get added to your project.
- You are now ready to go develop your Web API!
Note: The WebApi.All package includes the WebApi.Enhancements package that provides additional prototype features and components that can simplify your Web API implementation. These enhancements will be covered in a separate quick start. This quick start
focuses on the core Web API functionality.
3 – Creating the Contacts API class
- Right click on the ContactManager project and select Add->New Folder from the menu. Choose “APIs” as the folder name and hit “Enter”
- Right click on the APIs folder and choose Add->Class. Enter “ContactsApi” as the class name.
- Copy the code below into the new class.
using System.ServiceModel;
namespace ContactManager.APIs
{
[ServiceContract]
public class ContactsApi
{
}
}
The ServiceContractAttribute indicates to Web API that this class should be exposed over HTTP. Notice a using statement is added for “System.ServiceModel” which is where that attribute lives.
4 – Registering the Contacts API via routing
Our API needs to be hosted. In order to do this you will register it as an ASP.NET Route using ServiceRoute.
- Switch to the global.asax.cs file.
- Add the following two using statements at the top
using ContactManager.APIs;
using System.ServiceModel.Activation;
- In the RegisterRoutes method add the following line to register a route for your new Web API.
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
Add the entry as show below. This is important because MVC’s default route matches the first part of the URI as representing a controller. In this case our API does not correspond to a controller + action combo thus we place it first.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
ServiceRoute takes a path for the API which will be appended to the IIS base address as well as the host factory to use and the type of the API. In this case we specified “contacts” thus is will be hosted at “http://localhost:9000/api/contacts”.
Notice that contacts sits under a URI segement of “api”. The reasoning for this is to avoid conflicts between MVC routes as this route will always capture all traffic that starts with “api”.
Note: ServiceRoute has a known issue with that causes it to interfere with ASP.NET MVC action link generation. To work around this issue use WebApiRoute in WCF Web API Enhancements instead.
5 – Exposing contacts over an HTTP GET method.
In this part you will first create a POCO (Plain Old C#) Contact class which will contain the contact information that is passed back and forth between the API. It is essentially a DTO (Data Transfer Object) but in HTTP we consider the entity which is being
represented a “Resource”. You will then create a handler method for exposing that resource as an HTTP GET. This will allow multiple clients to access the resource.
- Right click on the ContactManager project and select Add->New Folder from the menu. Choose “Resources” as the folder name and hit “Enter”
- Create a new “Contact” class. Copy the code below into the class.
namespace ContactManager.Resources
{
public class Contact
{
public int ContactId { get; set; }
public string Name { get; set; }
}
}
- Now switch back to the ContactsApi class. Add the two using statements below:
using System.ServiceModel.Web;
using ContactManager.Resources;
- Now go implement a Get operation for retrieving all contacts by copying the code below.
[WebGet(UriTemplate = "")]
public IEnumerable<Contact> Get()
{
var contacts = new List<Contact>()
{
new Contact {ContactId = 1, Name = "Phil Haack"},
new Contact {ContactId = 2, Name = "HongMei Ge"},
new Contact {ContactId = 3, Name = "Glenn Block"},
new Contact {ContactId = 4, Name = "Howard Dierking"},
new Contact {ContactId = 5, Name = "Jeff Handley"},
new Contact {ContactId = 6, Name = "Yavor Georgiev"}
};
return contacts;
}
The WebGet attribute on the Get method indicates to Web API that this is to be exposed as an HTTP GET. Notice the UriTemplate is explicitly set to “”. By default the URI segment for the operation will be the method name. In this case
we are building a RESTful resource such that the URI segment will be the Web API itself as defined in the route.
6 – Retrieving contacts in the browser
- Double-click on the Properties node for the project and select the Web tab
- In the Start Action section select the Specific Page radio button and enter “api/contacts” in the corresponding text box
- Press F5 to launch the application
- When the browser finishes loading you will see the contact list returned as shown below.

7 – Test the Contacts API
Web API supports an integrated test client that can be used to test the Web API functionality. The Web API test client is enabled through configuration.
- In the RegisterRoutes method create an HttpConfiguration instance and set the EnableTestClient property to true.
var config = new HttpConfiguration() { EnableTestClient = true };
- Pass the configuration instance to the HttpServiceHostFactory for the Web API route by setting the Configuration property.
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory() { Configuration = config }, typeof(ContactsApi)));
- Press F5 and append “/test” to the browser address to bring up the Web API test client

- Click on the Contacts API URI in the Resources view to populate the Request fields for a simple GET request

- Click the Send button the issue the GET request and view the response

8 – Retrieving contacts in JSON
Web API supports what is known in HTTP as server driven content negotiation (conneg). This means clients can send an accept header in the HTTP request indicating alternative media types than XML which they would like the response to be returned in. Web API
also makes it very easy to add support for new media types, or to even replace the defaults. This will be covered in a future quick start.
- Browse to the Web API test client for the Contacts API if it is not still open
- Click on the Contacts API URI in the Resources view to populate the Request fields for a simple GET request
- Modify the Accept header value to be “application/json”

Notice the Web API test client provides IntelliSense for common media types
- Click the Send button to issue the Request and see the Response formatted as JSON

9 – Enabling OData query support
Web API supports the ability to accept a subset of the OData query URI format ($top, $skip, $orderby, and $filter). When an OData query request is received, Web API will apply the necessary filtering and ordering on the result before it is returned to the
client. It composes queries using IQueryable thus the server does not have to query all the data and can send a filtered query to the data source.
- Stop the application if it is running.
- Switch to ContactApi.cs.
- Add the following using statement
using System.Linq;
- Modify the Get method to return IQueryable<ContactResource>.
[WebGet(UriTemplate = "")]
public IQueryable<Contact> Get()
{
var contacts = new List<Contact>()
{
new Contact {ContactId = 1, Name = "Phil Haack"},
new Contact {ContactId = 2, Name = "HongMei Ge"},
new Contact {ContactId = 3, Name = "Glenn Block"},
new Contact {ContactId = 4, Name = "Howard Dierking"},
new Contact {ContactId = 5, Name = "Jeff Handley"},
new Contact {ContactId = 6, Name = "Yavor Georgiev"}
};
return contacts.AsQueryable();
}
- Run the application.
- Once the browser page loads, append the query string “?$top=4&$orderby=Name” to the address and press enter.
- The top four contacts are returned ordered by name.

- Browse to the test client and issue the same request with the same query string, but specify “application/json” in the Accept header
- Click the Send button and results are returned in JSON.

Summary
In this quick start we learned the following:
- How to add the Web API NuGet package (WebApi.All) to an existing project in order to use Web API.
- How to create a new Web API and host it over an HTTP GET Method
- How to return a resource from a Web API that can be represented in multiple formats
- How to retrieve data from a Web API in different formats by using the HTTP Accept header.
- How to enable OData query support.