Previous posts in this series:
… annnnnnd we’re back.
Based on the strengths of REST outlined in my last post in this series, it would be a good tool to add to our WCF service arsenal. Our web-based bagel bakery has been very successful, prompting the opening of new locations. Some of these locations are the traditional “counter service” type of bagel store that people are more accustomed to. Others are a café style with an expanded menu, fancy coffee and Internet access.
Our web page has a list of these locations, but as anyone invested in mobile development will tell you, you can’t have a successful business these days without having a smartphone application.A feature we would like for our smart phone application is a store locator. For now, we just want to provide a list of stores that the application can consume, but we don’t want this information hard-coded into the application, as it’s possible that any day now a large amount of venture capital will fall into our lap and we’ll want to open more stores
The best solution is to provide a web service that allows the application to access a current list of open stores at any time. To keep this service light weight and ensure that it is open to any smart phone platform we have decided to make this a REST based service. With WCF this is very easy.
Step One: The Service Contract
SOAP and REST based services are very different. The fact is that WCF was built on the idea of building SOAP based services and that is the focus of the classes in the System.ServiceModel assembly. In .NET 3.5 Microsoft added REST functionality to WCF in the form of the System.ServiceModel.Web assembly. This new assembly added some pieces that we will need to create our REST service.
Consider this service contract:

By now you should be able to easily determine that any service that implements this IStoreLocatorService contract must expose an action method called GetStores that returns a list of some Store objects. As is this is a standard WCF service an action that responds to an HTTP POST and returns a list of Stores in a SOAP message is created.
In order to tell WCF that we want this to be a REST based service we need to add an additional attribute to our operation:

The inclusion of the WebGet attribute in our service contract tells WCF that, depending on some configuration details, a service that implements this contract must be able to respond to an HTTP call with the GET verb (hence the “Get” in “WebGet”). For now don’t worry about the other verbs, we’ll get to them later.
There are several arguments we can pass into the WebGet attribute to change how this method behaves, but for now we’re just using the UriTemplate option. The UriTemplate tells WCF what the URI that access this service should look like. In this case we’re telling WCF that if the base address of our service is “www.WebBagels.com” and the client uses that as it’s URI it will access this method via a pattern match. If we were to make a small change to the UriTemplate for our service….

… our service will now be called if the client attempts to access the www.WebBagles.com/Stores URI.
That’s pretty nifty, but what happens if a user is specifically looking for one of our “café” stores? Users are going to want a way to filter this list. And besides, one of the big benefits of REST is supposed to be the cacheable, easy to understand hierarchical way of representing data, right?
WCF makes if very easy, again using a simple pattern matching algorithm to enable us to have dynamic arguments embedded in our URI. We’ll add a new method to our service contract that enables users to search for specific store types:

Our new method still responds to an HTTP GET, but we’ve added a second UriTemplate with a different patters to match. In our GetStoresByStoreType method we are now looking for a URI that includes the store type of the stores we are searching for.
The first thing I had to do was create a new method called GetStoresByStoreType that took a string parameter of storeType. It’s important to note that when you are using parameterized URI’s like we are here, the arguments for your method MUST all be strings; no other types are allowed. The reason is that the URI itself is a string and all constituent parts of it must be treated as strings as well. You can cast them all you want once they are passed into your method, but the method prototype must define these as strings. Aside from that you need to make sure that the token you are using in the UriTemplate (in this case {storeType}) matches the name of the parameter you want to map it to, including capitalization. Order is unimportant and if the URI has a token that does not map to a parameter on your method WCF will just ignore it. On the other hand if you have a parameter for your method that does not map to a token in your UriTemplate .NET will throw an error since it is missing parameters for the method call.
Based on this service contract we will have two URI’s that our service is able to respond to:
- www.WebBagles.com/Stores – Results in a call to the GetStores method, returns a list of all stores.
- www.WebBagles.com/Stores/{storeType} – Results in a call to the GetStoresByStoreType method, returns a filtered list of stores.
One last thing to notice here: The names of the .NET methods in our service contract has no bearing on or relationship to our URI’s. We could call those two methods anything we want (provided it’s a name .NET deems legal) and as long as our URI templates don’t change our clients would never know. This means that once we expose an API we can refactor internally all we want so long as we don’t change (mess up) those UriTemplates and break the API.
By default WCF returns POX (Plain Ol’ XML) for it’s REST methods. Most users, myself included, would rather consume this information as JSON (JavaScript Object Notation) in many, if not most situations. For one thing as a web developer I find myself taking more and more advantage of AJAX calls from the browser. In these cases I would much rather consume the native JSON object than futz with the JavaScript XML parser.
Having said that there are a lot of applications that consume REST services from C# or VB.NET and XML seems to be the more popular choice in those languages. As a result I like to write my REST services in a way that enables the users to determine how they get the data back (POX or JSON). For this service I’ll do that by adding a two new operation contracts to my IStoreLocatorService service contract; one to return all stores as a list of JSON objects and another to return list of stores filtered by store type as JSON objects:

First let’s compare the contract for GetStores to the one for GetStoresInJson. The UriTemplate for GetStoresInJson is the same as the UriTemplate for the GetStores contract, except that I’ve added “/js” to the end. When WCF sees a request for a URI that looks like “~/Stores/js” it knows to route that action to the GetStoresInJson method since the incoming URI matches the pattern defined in the WebGet attribute of the GetStoresInJson method. Similarly, the GetStoresByStoreTypeInJson method is able to respond to requests that have URI’s with the pattern of “~/Stores/{storeType}/js” as opposed to “~/Stores/{storeType}” mapping those actions to the GetStoresByStoreType method which returns POX.
The other change to note is that unlike the previous methods we worked with (GetStores and GetStoresByStoreType) we’ve added a new parameter to the WebGet attribute; ResponseFormat. As you can probably infer from it’s name, it’s used to tell WCF how you want the response from the service formatted. As I mentioned before the default is POX, but by specifying a value for the ResponseFormat (in this case WebMessageFormat.Json) we can change how the data is returned. As you may guess there is a corollary parameter, RequestFormat that specifies how the service should expect incoming request data to be formatted, but I’ll get into that in a future post.
I’ve talked quite a bit about the service contact side of building these REST based services, but I haven’t touched on the implementation. That’s because the vast majority of the work to make these WCF services RESTful is done in the service contract. Here are the implementations for GetStores and GetStoresInJson:

As you can see, there isn’t really much to these implementations. The methods just return a list of Store objects. The GetStoresByStoreType and GetStoresByStoreTypeInJson just use a LINQ query to get the specific stores that match the store type out of the ListOfStores list. WCF, via the definition in the service contract will serialize this as either POX or JSON when it’s returned.
Step Two: The Data Contract
So how about that Store object? Like all complex structures that are sent received via WCF services, the easiest way to deal with it is to create a Data Contract. The Data Contract for our REST based service is very similar to the data contracts we’ve created for the other services in this series:

Like the previous data contracts this one has a class level attribute of DataContract and each property that I want to expose via the service is decorated with a DataMember attribute. In this case I have added a Namespace parameter to the DataContract attribute at the class level. I’ll explain why and more about namespaces in a future post.
Step Three: Updating the Host
The previous services in this series were all SOAP services. As a result we were able to use the ServiceHost class to host those services. Since REST services live by a different set of rules than SOAP services, particularly the use of parameterized URI’s REST services needs a host with slightly different capabilities than the one used for SOAP services.
WCF provides the WebServiceHost class for hosting REST based web services. As you can see from this code snippet, it’s just as easy to use as the ServiceHost class:

Now that we have our hosting situation sorted out, it’s time to look as our configuration.
Step: Four: Updating the configuration
Since we’ve added a new service to our solutions, we need to add a new service section to our configuration. We already did this for our SOAP service and our REST service is actually pretty easy by comparison:

The address attribute identifies the base address for our service. The URI Template from our service contract is appended to this base URI in the configuration. This means that the URI we will use to get to the list of stores is http://localhost:8733/Stores. To search by store type the URI would be http://localhost:8733/Stores/<store type being searched>.
For binding we’ll need to use the webHttpBinding. This is a REST specific binding and will tell WCF to build a channel stack that includes the serializers for POS and JSON messages. Contract behaves exactly the same way it has for our SOAP services.
This configuration works for our self-hosted service. For hosting REST based WCF services in IIS you will need to make a couple more small changes. I’ll cover those configuration changes in a few posts when I cover deployment.
Step Five: Testing and Profit
To test our SOAP services we either had to use the WCF test client of write an application that created a proxy object that would serialize and send SOAP messages as POST actions and deserialzie the SOAP messages that were returned. Since REST based services are HTTP based and don’t reply with complex SOAP messages we can easily test our service in any web browser. To test our service I’ll start by launching the hosting application:

I’ll fire up Chrome (I prefer Chrome over IE for this, you’ll see why in a minute) and put the URI for our Stores REST service into the address bar (this is the base address from the configuration of the endpoint plus the URI template from the service contract) and hit Enter. Since our service just returns POX, we have not problem being able to view the message in Chrome (or any browser for that matter) without our faces melting:

To filter this down by store type we can add the store type to the URI as proscribed by the URI template in the operation contract for the GetStoresByStoreType method of our Service Contract:

WCF mapped the URI with the store type data to the correct method that filtered the store data by store type. What happens if we supply a store type that has no stores:

We simply got an empty list back. This is the preferred way REST services should handle this type of situation; if there is no data that satisfies the query then return an empty result.
Say we want JSON. As we provided additional Operation Contracts that specified JSON as the response format when “/js” was added to our URI we simply need to add that to our current URI to change the format of the response data:

Line-breaks aside, JSON is a pretty easy format to understand and digest. Incidentally, JSON services are why I prefer to use Chrome for this kind of testing as opposed to Internet Explorer. For whatever reason IE does not want to render JSON and instead will make you save it to a file which you then will have to open in a text editor:

The end result is the same, but I appreciate that Chrome doesn’t make me go through this extra step to see my data.
You may have noticed that we didn’t work much with query strings here. That will be covered in a future post.
In the next post we’ll see how to send data to our service with the POST verb and lean how to test our services with one of my favorite all time developer tools.
Code on!