Pre-requisites

Code

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.

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.

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”

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.

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

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.

I have been working through the WCF samples with the goal of using WCF Web Api for a new project. I quickly ran into challenges with Entity Framework (EF). It seams the WCF Web Api doesn't support POCO classes that have been used in an EF repository.

Nice example. I went ahead and posted code to turn this MVC example into a self-hosted example. You can find the code here: http://codebetter.com/johnpetersen/2012/01/13/webapi-developer-preview-6-self-hosted-mode-example/.

Im getting an error when opening your code files in Visual Studio 2010, also see my post on it here: http://forums.asp.net/p/1743303/4700104.aspx/1?Re+Visual+Studio+2010+The+project+type+is+not+supported+by+this+installation+If possible could you report the code files?Thanks!

I did this exercise, but returned some data from an EF model rather than the hard coded resources. Works great in browser and in test client, but when I change the accept header to application/json, I get response 12152/Unknown.

(Sorry for my bad english)I follow the tutorial and all is working great but what do I need to do to be able to use $select on the query? Something like this:http://localhost:9000/api/contacts?$select=Nameshould return only the Name but are returning all fields.

Great walkthrough. One minor thing is that we have added a class (resource) Contact and not ContactResource. At part VI we have to modify the get method:"Modify the Get method to return IQueryable<ContactResource>" --> The name of the class should be renamed to ContactResource or change to IQueryable<Contact>.

In the several tests I just performed I consistently get the same behavior of:

1) If I right-click on the PROJECT and use “Manage NuGet Packages…" then all references and the Web.config are setup and all works with WebApi.All as expected.

2) If I right-click on the SOLUTION and use “Manage NuGet Packages…" to add WebApi.All then the references are not added to the project, and packages.config and Web.config are not modified. If I manually re-launch “Manage NuGet Packages…" at the SOLUTION level, go to WebApi.Core, push the Manage button, and select the “ContactManager” project, then all things get wired up as expected.

So for me, using NuGet 1.4 at the project level is easiest for this sample.

This may be by design or it may just be my system that needs a reinstall. Oh well : )

Here is some system detail in case others have these issues and it warrants more troubleshooting:

I sounds like I need to test this with the latest nuget as things that should work did not work for you.

1. On the "Manage NuGet Packages" thanks for the pointer. Others told me about that. They did not have the same problems you did though with the references.2. You should not have to add any manual references. The nuget pack contains intstructions to add Gac'd references.3. You should not have to modify the config as the nuget contains a transformation for modifying config.

Here are some things I had to work through to use the example that may help others:

Part IIWhen you try this step:[Right click on the solution and select “Add Library Package Reference”]

If you are using the latest NuGet (1.4) you will not see “Add Library Package Reference”.You will see, “Manage NuGet Packages…" instead.

If you are using NuGet 1.4, although these instructions suggest that you right-click on the SOLUTION to use NuGet, I would recommend that for this example you right-click on the PROJECT “ContactManager” instead and select “Manage NuGet Packages…" from there.

Why? Because NuGet 1.4 added some new features to allow you to better manage multi-project solutions but on my system when I tried to add WebApi.All at the SOLUTION level, NuGet by default did NOT add the DLL references to the “ContactManager” project. In older versions of NuGet those references were added to my sub-projects automatically even if I used “Add Library Package Reference” at the solution level. I am not sure if this is just an issue on my machine but if you find yourself wondering why your using statements can’t be resolved or this example won’t run without throwing exceptions you may want to make sure that your “ContactManager” PROJECT actually has the many dll references that are currently required to use the WCF Web Api in its current state.

Some other things to be aware of that may not be obvious at first glance if you are new to WCF and the WCF Web Api like I am:

In Part III you need to manually add a reference to “System.ServiceModel” in the “ContactManager”project as it is part of the .NET Framework and not automatically referenced for you with NuGet.

In Part V you need to manually add a reference to “System.ServiceModel.Web” in the “ContactManager”project as it is part of the .NET Framework and not automatically referenced for you with NuGet.

In Part VI when I pressed F5 to launch the application I received an exception:“InvalidOperationException” “ASP.NET routing integration feature requires ASP.NET compatibility.”I had to add the following to the “ContactManager”’s Web.config file in order to run the application and continue on with the exercises.