Professional Documents
Culture Documents
A Developer WCF
A Developer WCF
Aaron Skonnard, Pluralsight August 2009 NOTE: This paper is based on the WCF REST Starter Kit Preview 2 release.
Overview
Windows Communication Foundation (WCF) 3.5 introduced a Web programming model for building RESTful services in .NET. Although WCF 3.5 lays a solid foundation for building a wide-variety of RESTful services, it still requires developers to implement a great deal of boilerplate code for each RESTful service they build and to deal directly with important HTTP protocol features. The WCF REST Starter Kit provides a set of WCF extensions and project templates that aim to simplify REST development even further. Although the WCF REST Starter Kit is currently considered a preview technology, many of its features will most likely find their way into future versions of the .NET Framework. In this whitepaper, well fully explore the various WCF REST Starter Kit features and show you how can begin putting them to good use to handle some of the most common REST development scenarios today. Microsoft is committed to offering a rich platform for RESTful services as part of Microsoft .NET. If youre unfamiliar with REST concepts or the WCF 3.5 REST programming model, be sure to read A Guide to Designing and Building RESTful Services with WCF 3.5 before proceeding.
Assembly Name
Description
Microsoft.ServiceModel.Web Contains a set of new classes and extension methods that simplify the process of building and hosting RESTful services using WCF. Microsoft.Http Contains a set of new classes and extension methods that simplify the process of consuming RESTful services using HTTP. Contains a set of new classes and extension methods for consuming specific types of RESTful services and response formats.
Microsoft.Http.Extensions
Figure 1: WCF REST Starter Kit Assemblies The Microsoft.ServiceModel.Web assembly contains a new WebServiceHost2 class (derived from WebServiceHost in WCF 3.5) designed specifically for hosting RESTful services. This class bootstraps several REST-specific features and configures the underlying WCF runtime in a way that will ultimately make your RESTful services easier to build and easier for others to consume. This new assembly also comes with some .NET attributes and extension methods that you can also take advantage of in your code. These extensions allow you to tap into the various features offered by WebServiceHost2. The Microsoft.Http assembly contains a new client-side HTTP API for consuming RESTful services. The primary class of interest in this assembly is HttpClient. With HttpClient, you can easily issue HTTP GET, POST, PUT, and DELETE requests and process the response through a variety of different content-specific APIs. It also makes it easier to send form data and query string values, and it simplifies the process of working with HTTP headers through a new set of typed header classes. This new client-side API provides a more natural HTTP experience for consuming any RESTful service found on the Web. And finally, the Microsoft.Http.Extensions assembly contains a few specialized HttpClientderived classes that focus on specific scenarios. It also provides quite a few extension methods focused on processing the body of an HTTP message in a variety of different formats (XML, JSON, Atom feed, etc). Youll take advantage of these extension methods in conjunction with HttpClient when consuming a service. The WCF REST Starter Kit also comes with a set of helpful Visual Studio project templates (see Figure 2) that target common REST scenarios. These project templates provide the boilerplate code you need to get started, taking advantage of the new classes/extensions found in the assemblies described above. For example, theres a template for producing a singleton service (exposes a single resource) and another for producing a collection service (exposes a collection of resources). Theres another template for producing an Atom feed and another that produces a fully functional AtomPub service. These templates can help jump-start your service implementation for these different REST scenarios.
Project Template
Description
REST Singleton Service REST Collection Service Atom Feed Service AtomPub Service HTTP Plain XML Service
Produces a service that defines a sample singleton resource (SampleItem) and the full HTTP interface for interacting with the singleton (GET, POST, PUT, and DELETE) with support for both XML and JSON representations. Similar to the REST Singleton Service only it also provides support for managing a collection of SampleItem resources.
Produces a service that exposes a sample Atom feed with dummy data.
Produces a fully functional AtomPub service capable of managing collections of resources as well as media entries. Produces a service with simple GET and POST methods that you can build on for plainold XML (POX) services that dont fully conform to RESTful design principles, but instead rely only on GET and POST operations.
Figure 2: WCF REST Starter Kit Project Templates In the sections that follow, well dive into these assemblies and project templates in more detail and along the way well look at how to handle some common REST scenarios.
VB C# C++ F# JScript
In order to begin using the WCF REST Starter Kit features with your service, all you need to do is change the class name from WebServiceHost to WebServiceHost2 in your code:
VB C# C++ F# JScript
You can also take advantage of WebServiceHost2 when hosting services in IIS. If youre hosting your WCF services inside of IIS today, youll have an SVC file that looks something like this:
<%@ ServiceHost Language="C#" Debug="true" Service="BookmarkService" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>
The WCF REST Starter Kit comes with a new WebServiceHost2Factory class its responsible for activating WebServiceHost2 instances. Simply replace the factory class with WebServiceHost2Factory and your IIS-hosted services will be managed by WebServiceHost2 instances automatically:
<%@ ServiceHost Language="C#" Debug="true" Service="BookmarkService" Factory="Microsoft.ServiceModel.Web.WebServiceHost2Factory"%>
So what exactly does WebServiceHost2 do differently than the WebServiceHost class that comes with WCF 3.5? It does two key things. First, it replaces the WebHttpBehavior on all endpoints with an instance of WebHttpBehavior2. The new WebHttpBehavior2 class is responsible for providing the automatic help page functionality and the server Web error handling logic. Second, it adds a new binding element to each endpoint to inject the new request interception logic. So by simply changing the host type, your WCF REST services will be able to take advantage of these new features.
Figure 3: Automatic help page for RESTFul services Its important to note that the help page is returned as an Atom feed. Most Web browsers provide built-in feed rendering to facilitate human viewing, which is what Internet Explorer is doing in Figure . However, since its a feed, consumers can also programmatically consume the description if desired. If you were to turn off the feed reading view in the Internet Explorer options, youd actually see the feed XML rendered instead you can also inspect the feed XML by viewing the source of the page. By default, the help page is made available at the base address with help appended to the end but you can customize the help page address through the HelpPageLink property on WebServiceHost2. You can also add a human readable description to each RESTful operation through the new [WebHelp] attribute found in Microsoft.ServiceModel.Web, as illustrated in the following example:
VB C# C++ F# JScript
[WebHelp(Comment = "Returns the user account details for the authenticated user.")] [WebGet(UriTemplate = BookmarkServiceUris.User)] [OperationContract] User GetUserAsXml(string username) { return HandleGetUser(username); }
Now when you rerun the host application and browse back to the help page, youll see this comment text appear within the GetUserAsXml description (see Figure 4).
Figure 4: Automatic Help Page with Custom Description This new help page automatically makes your RESTful services more discoverable, which ultimately makes them easier for others to consume. Your consumers can discover the services URI design, the supported HTTP operations, and the request/response formats, and your description will always stay in sync with your WCF code similar to how things worked with ASP.NET Web Services. You still dont get a full client-side code generation experience (a la WSDL) but when you combine this help page with the new HttpClient functionality, you really dont need it.
ExceptionHandling
One of the more tedious aspects of implementing RESTful services is dealing directly with some of the HTTP protocol details, like returning the appropriate HTTP status codes and descriptions, especially within the context of a WCF service operation. The following code illustrates how to check for unauthorized users and it returns a 401 Unauthorized response when necessary:
VB C# C++ F# JScript
This code isnt terribly difficult but it also doesnt return a detailed response message, which is typically very helpful for consumers. When you want to return this type of detailed response message, the complexity goes up significantly because theres not an easy way to do it within the WCF operation. In order to simplify this common scenario, the WCF REST Starter Kit provides a new WebProtocolException class that makes it really easy to return an HTTP error to the caller. You
simply throw an instance of WebProtocolException within your WCF service operations, specifying the HTTP status code and error message, and (assuming youre using WebServiceHost2) the underlying runtime takes care of producing the appropriate HTTP response message. The following example illustrates how to throw a few different WebProtocolException instances specifying different HTTP status codes and error messages:
VB C# C++ F# JScript
if (!IsUserAuthorized(username)) { throw new WebProtocolException(HttpStatusCode.Unauthorized, "Missing or invalid user key (supply via the Authorization header)", null); } if (bookmark_id <= 0) throw new WebProtocolException(HttpStatusCode.BadRequest, "The bookmark_id field must be greater than zero", null);
After a WebProtocolException is thrown, it will be handled by a custom WCF error handler (introduced by the WebHttpBehavior2). The error handler translates the WebProtocolException instance into an appropriate HTTP response message containing a detailed response for the consumers benefit. Figure 5 illustrates what the first WebProtocolException looks like when rendered in a browser. Notice how the resulting XHTML clearly displays the HTTP status code along with a detail message. This standard XHTML template is built into the WebProtocolException class so if you like the way it works, you dont have to do anything further and your consumers will receive something reasonable.
Figure 5: WebProtocolException Rendered in a Browser If, however, youd like to customize the resulting XHTML, you can use one of the other constructor overloads and supply the precise XHTML youd like to return as illustrated here:
VB C# C++ F# JScript
if (!IsUserAuthorized(username)) { throw new WebProtocolException(HttpStatusCode.Unauthorized, "Unauthorized", new XElement("html", new XElement("body"), new XElement("h1", "Unauthorized"), new XElement("p", "Missing or invalid user key " + "(supply via the Authorization header)")), true, null); }
Figure 6 shows the results of throwing this WebProtocolException when rendered in a browser:
Figure 6: WebProtocolException with Custom XHTML Response This approach gives you complete freedom over the response XHTML. However, if youre not concerned with returning a human-readable error message (in XHTML), you can instead return a custom type that will be serialized into XML (using DataContractSerializer). The following code example illustrates how to accomplish this using a custom type called CustomErrorMessage:
VB C# C++ F# JScript
if (!IsUserAuthorized(username)) { throw new WebProtocolException(HttpStatusCode.Unauthorized, "Custom error message", new CustomErrorMessage() { ApplicationErrorCode = 5000, Description = "Authentication token missing" }, null); }
In this case, the consumer receives the custom XML message illustrated in Figure 7.
Figure 7: WebProtocolException with a Custom XML Response Furthermore, if the WCF operation specifies WebMessageFormat.Json for the response, the resulting XML will be serialized using the DataContractJsonSerializer in order to return JSON to the consumer. You can even take things one step further by integrating with the ASP.NET custom error feature. You can accomplish this by adding some code to Global.asax to check for the existence of a WebProtocolException and to redirect the consumer to a custom error page when it finds one:
VB C# C++ F# JScript
protected void Application_EndRequest(object sender, EventArgs e) { if (HttpContext.Current.Error != null) { WebProtocolException webEx = HttpContext.Current.Error as WebProtocolException; if (webEx != null && webEx.StatusCode == HttpStatusCode.BadRequest) { HttpContext.Current.ClearError(); HttpContext.Current.Response.Redirect("BadRequest.htm"); }
There are two samples in the WCF REST Starter Kit SDK that illustrate how these WebProtocolException features work one called WebException and another called WebException2. In the end, these features make it much easier to produce custom HTTP error messages containing descriptive response messages by simply throwing exceptions, which is a more natural model for .NET developers.
Caching Support
One of the primary potential benefits of REST is HTTP caching. However, in order to realize that benefit, you have to leverage the various HTTP caching headers in your request and response messages. You can accomplish this within your WCF service operations by manually accessing the request/response headers through the WebOperationContext instance but its not trivial to do properly. The WCF REST Starter Kit also provides a simpler model for controlling caching through the [WebCache] attribute that you can declaratively apply to your various GET operations. This attribute allows you to specifying a caching profile for each operation and then the caching behavior (CachingParameterInspector) takes care of handling all of the underlying HTTP caching details. The [WebCache] implementation builds on ASP.NET output caching and provides most of the same properties found on the System.Web.UI.OutputCacheParameters class. It simply integrates that same behavior with the WCF runtime and makes it easy to declaratively apply that behavior to your WCF service operations. The following example shows how to cache a [WebGet] response for 60 seconds:
VB C# C++ F# JScript
[WebCache(Duration = 60)] WebGet(UriTemplate = BookmarkServiceUris.PublicBookmarks)] OperationContract] ookmarks GetPublicBookmarksByTagAsXml(string tag) return HandleGetPublicBookmarks(tag);
However, since this operation can return a different response for each supplied tag, we really want to vary the cached response on a tag-by-tag basis. You can accomplish this by using the VaryByParam property (which you may be familiar with from ASP.NET) as illustrated here:
VB C# C++ F# JScript
[WebCache(Duration = 60, VaryByParam = "tag")] [WebGet(UriTemplate = BookmarkServiceUris.PublicBookmarks)] [OperationContract] Bookmarks GetPublicBookmarksByTagAsXml(string tag) { return HandleGetPublicBookmarks(tag); }
In addition to VaryByParam, the [WebCache] attribute provides VaryByHeader and VaryByCustom, which allow you to specify different variables for influencing the output cache entry. You can also use the Location to control where the response is allowed to be cached (e.g., Any, Client, Server, ServerAndClient etc), and to prevent caching altogether, you can set the NoStore property to true. [WebCache] also supports the CacheProfile property, which allows you to reference an output cache profile found in web.config. For example, the following web.config contains an output cache profile called CacheFor1Min that specifies the response will be cached for 60 seconds,
the cached response can be stored anywhere, and the cache entry will vary by the tag parameter:
<configuration> <system.web> <compilation debug="true"/> <caching> <outputCacheSettings> <outputCacheProfiles> <clear/> <add name="CacheFor1Min" duration="60" enabled="true" location="Any" varyByParam="tag"/> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel> </configuration>
This allows you to decouple the caching behavior from your compiled WCF code. You can apply this output cache profile to your WCF operations through the [WebCache] attribute as shown here:
VB C# C++ F# JScript
And finally, the [WebCache] attribute even allows you to tie the caching behavior to a SQL dependency through the SqlDependency property. In order to take advantage of this, you need to add a <sqlCacheDependency> entry for the database in question to web.config. Then you use the
[WebCache] attributes SqlDependency property to specify a list of database & table name pairs that the cache entry should depend on. The cache entry will expire when any of the specified tables are modified. The following web.config illustrates how to configure a new <sqlCacheDependency> entry:
<configuration> <connectionStrings> <add name="bmconn" connectionString= "Data Source=.; Initial Catalog=BookmarksDB; Integrated Security=true" /> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="1000" > <databases> <add name="bmdb" connectionStringName="bmconn" /> </databases> </sqlCacheDependency> </caching> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel> </configuration>
Then you can apply [WebCache] to an operation to tie the output caching behavior to a specific table within the SQL database. The following example ties the output caching to the Bookmarks table:
VB C# C++ F# JScript
[WebCache(SqlDependency="bmdb:Bookmarks", VaryByParam = "tag")] WebGet(UriTemplate = BookmarkServiceUris.PublicBookmarks)] OperationContract] ookmarks GetPublicBookmarksByTagAsXml(string tag) return HandleGetPublicBookmarks(tag);
With this in place, the output of this particular operation will be cached (for each unique tag) until the data in the underlying Bookmarks table changes. The [WebCache] attribute makes it much easier for you to take advantage of HTTP caching without requiring you to work with the HTTP caching headers directly. The underlying WCF behavior takes care of injecting the HTTP Cache-Control, Date, Expires, and Vary HTTP headers in the response, which clients can then take advantage of to cache the response and reduce the number of future round-trips. The WCF REST Starter Kit SDK comes with two complete samples that illustrate how to work with the [WebCache] feature in more detail one called Caching1 and another called Caching2 the Caching2 sample provides a complete example using a SQL cache dependency. In addition to the [WebCache] feature, the WCF REST Starter Kit also comes with a few extension methods that make it easier to work with ETags, which simplify the process of implementing conditional GET and conditional PUT scenarios. Ill show you an example of this later in the paper.
Request Interception
Another common need when building RESTful services is request interception. For example, when you need to implement a service behavior that is going to apply to all operations (such as authentication or custom dispatching logic), its usually best to implement it as a WCF behavior since the behavior model allows you to inject a request processing interceptor into the runtime. The only problem is writing WCF behaviors and interceptors is fairly complex and not for the faint of heart. Hence, in order to simplify this common scenario, the WCF REST Starter Kit provides a much simpler request interception mechanism that shields you from writing the more complex WCF extensibility components. Within Microsoft.ServiceModel.Web, youll find a new abstract base class called RequestInterceptor that defines a single abstract method called ProcessRequest. Heres the full class definition:
VB C# C++ F# JScript
public abstract class RequestInterceptor { protected RequestInterceptor(bool isSynchronous); public bool IsSynchronous { get; } public virtual IAsyncResult BeginProcessRequest(RequestContext context, AsyncCallback callback, object state); public virtual RequestContext EndProcessRequest(IAsyncResult result); public abstract void ProcessRequest(ref RequestContext requestContext); }
You derive a class from RequestInterceptor and override ProcessRequest (and BeginProcessRequest/EndProcessRequest if you want to support asynchronous calls). Your implementation of ProcessRequest is where you implement the request interception logic. Notice youre supplied a Request Context instance, which gives you access to the request message and provides a few methods for short-circuiting the request pipeline and returning a response message. The WebServiceHost2 class manages the collection of RequestInterceptor instances configured for a particular service. You simply add RequestInterceptor instances to the Interceptors collection before calling Open on the host instance. Then when you call Open, they will be inserted into the request processing pipeline behind the scenes (through a new binding element). The following example shows how to implement a RequestInterceptor that performs API key authentication and rejects unauthorized requests:
VB C# C++ F# JScript
public override void ProcessRequest(ref RequestContext requestContext) { if (!IsValidApiKey(requestContext)) GenerateErrorResponse(requestContext, HttpStatusCode.Unauthorized, "Missing or invalid user key (supply via the Authorization header)"); } public bool IsValidUserKey(Message req, string key, string uri) { ... // ommitted for brevity } public void GenerateErrorResponse(RequestContext requestContext, HttpStatusCode statusCode, string errorMessage) { // The error message is padded so that IE shows the response by default string errorHtml = "<html><HEAD><TITLE>Request Error</TITLE></HEAD><BODY>" + "<H1>Error processing request</H1><P>{0}</P></BODY></html>"; XElement response = XElement.Load(new StringReader( string.Format(errorHtml, errorMessage))); Message reply = Message.CreateMessage(MessageVersion.None, null, response); HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty() { StatusCode = statusCode }; responseProp.Headers[HttpResponseHeader.ContentType] = "text/html"; reply.Properties[HttpResponseMessageProperty.Name] = responseProp; requestContext.Reply(reply); // set the request context to null to terminate processing of this request requestContext = null; } }
Now, you can take advantage of this request interceptor with your IIS-hosted services by writing a custom ServiceHostFactory that injects the interceptor when the WebServiceHost2 instance is first created. The following example illustrates how to accomplish this:
VB C# C++ F# JScript
public class SecureWebServiceHostFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { WebServiceHost2 host = new WebServiceHost2(serviceType, true, baseAddresses); host.Interceptors.Add(new AuthenticationInterceptor()); return host; } }
Then you simply specify SecureWebServiceHostFactory in your .svc files (using the Factory attribute) and your interceptor will automatically kick in. This turns out to be much easier than writing the equivalent WCF behavior, interceptor, and attribute classes that would be necessary to pull this off. The WCF REST Starter Kit SDK comes with a few additional examples that illustrate some of the possibilities with RequestInterceptor. One of the samples shows how to implement X-HTTPMethod-Override behavior with a RequestInterceptor. Heres the RequestInterceptor implementation:
VB C# C++ F# JScript
public class XHttpMethodOverrideInterceptor : RequestInterceptor { public XHttpMethodOverrideInterceptor() : base(true) {} public override void ProcessRequest(ref RequestContext requestContext) { if (requestContext == null || requestContext.RequestMessage == null) { return;
} Message message = requestContext.RequestMessage; HttpRequestMessageProperty reqProp = (HttpRequestMessageProperty) message.Properties[HttpRequestMessageProperty.Name]; string methodOverrideVal = reqProp.Headers["X-HTTP-Method-Override"]; if (!string.IsNullOrEmpty(methodOverrideVal)) { reqProp.Method = methodOverrideVal; } } }
It looks for the X-HTTP-Method-Override header and if it finds one, it resets the HTTP method for the request message to the value found in the header. This provides for a very simple solution to this scenario and it can easily be reused across all of your RESTful WCF service solutions. Another RequestInterceptor example they provide with the WCF REST Starter Kit is contenttype-based dispatching. In other words, making it possible to dispatch to different service operations based on the value of the HTTP Accept or Content-Type request headers. The following example shows how you can accomplish this through another RequestInterceptor implementation:
VB C# C++ F# JScript
public class ContentTypeRequestInterceptor : RequestInterceptor { public ContentTypeRequestInterceptor() : base(true) {} public override void ProcessRequest(ref RequestContext requestContext) { if (requestContext == null) return; Message request = requestContext.RequestMessage; if (request == null) return; HttpRequestMessageProperty prop = (HttpRequestMessageProperty) request.Properties[HttpRequestMessageProperty.Name]; string format = null; string accepts = prop.Headers[HttpRequestHeader.Accept]; if (accepts != null)
{ if (accepts.Contains("text/xml") || accepts.Contains("application/xml")) { format = "xml"; } else if (accepts.Contains("application/json")) { format = "json"; } } else { string contentType = prop.Headers[HttpRequestHeader.ContentType]; if (contentType != null) { if (contentType.Contains("text/xml") || contentType.Contains("application/xml")) { format = "xml"; } else if (contentType.Contains("application/json")) { format = "json"; } } } if (format != null) { UriBuilder toBuilder = new UriBuilder(request.Headers.To); if (string.IsNullOrEmpty(toBuilder.Query)) { toBuilder.Query = "format=" + format; } else if (!toBuilder.Query.Contains("format=")) { toBuilder.Query += "&format=" + format; } request.Headers.To = toBuilder.Uri; } } }
These are just a few examples of what you can accomplish with the RequestInterceptor mechanism. You can use this technique to accomplish a variety of different request processing behaviors such as logging, validation, or even custom caching. And the solution is easy to reuse across your RESTful services.
methods are scattered across several classes within Microsoft.ServiceModel.Web. Ill highlight a few of them here. The WebOperationContextExtensions class contains a set of extension methods for the core WebOperationContext class. A few of them are designed to make URI and UriTemplate manipulation easier (GetBaseUri, GetRequestUri, and BindTemplateToRequestUri). And the rest are designed to simplify HTTP ETag processing (through several SetHashEtag overloads and ThrowIfEtagMissingOrStale). The following shows the class definition for WebOperationContextExtensions:
VB C# C++ F# JScript
public static class WebOperationContextExtensions { public static Uri BindTemplateToRequestUri(this WebOperationContext context, UriTemplate template, params string[] values); public static Uri GetBaseUri(this IncomingWebRequestContext context); public static NameValueCollection GetQueryParameters( this IncomingWebRequestContext context); public static Uri GetRequestUri(this IncomingWebRequestContext context); public static string SetHashEtag<T>(this OutgoingWebResponseContext context, T entityToHash); public static string SetHashEtag<T>(this OutgoingWebResponseContext context, BinaryFormatter formatter, T entityToHash); public static string SetHashEtag<T>(this OutgoingWebResponseContext context, XmlObjectSerializer serializer, T entityToHash); public static string SetHashEtag<T>(this OutgoingWebResponseContext context, XmlSerializer serializer, T entityToHash); public static void ThrowIfEtagMissingOrStale( this IncomingWebRequestContext context, string expectedEtag); }
The SerializationExtensions class contains several extension methods that simplify serializing objects to and from XElement instances (when using XLinq). It provides several ToObject and ToXml overloads:
VB C# C++ F# JScript
public static class SerializationExtensions { public static TObject ToObject<TObject>(this XElement xml); public static TObject ToObject<TObject>(this XElement xml, XmlObjectSerializer serializer); public static TObject ToObject<TObject>(this XElement xml, XmlSerializer serializer); public static XElement ToXml<TObject>(TObject obj); public static XElement ToXml<TObject>(TObject obj, XmlObjectSerializer serializer); public static XElement ToXml<TObject>(TObject obj, XmlSerializer serializer); }
And finally, the SyndicationExtensions class contains several extension methods that simplify working with RSS/Atom feeds through the SyndicationFeed and SyndicationItem classes. These methods make it easier to add various types of links to a feed including self links, edit links, and navigation links:
VB C# C++ F# JScript
public static class SyndicationExtensions { public static void AddEditLink(this SyndicationItem entry, Uri uri); public static void AddEditMediaLink(this SyndicationItem entry, Uri uri, string contentType, long contentLength); public static void AddNextPageLink(this SyndicationFeed feed, Uri uri); public static void AddPreviousPageLink(this SyndicationFeed feed, Uri uri); public static void AddSelfLink(this SyndicationFeed feed, Uri uri); }
In addition to these extension methods, the Microsoft.ServiceModel.Web.SpecializedServices namespace also contains a set of service contract interfaces and base class definitions for some of the most common types of specialized RESTful services (see Figure 8). Here youll find types for singleton services, collection services, and AtomPub services.
Interface
Base Class
Description
ISingletonService<TItem> SingletonServiceBase<TItem> Defines a generic service contract and base implementation for singleton REST services, e.g. a RESTful service that only exposes a single TItem resource. ICollectionService<TItem> CollectionServiceBase<TItem> Defines a generic service contract and base implementation for collection REST services, e.g. a RESTful service that exposes a collection of TItem resources. IAtomPubService AtomPubServiceBase Defines a generic service contract and base implementation for AtomPub services.
Figure 8: Specialized REST Service Contract Interfaces and Base Classes These types define the REST contract details for each type of service, shielding you from the HTTP details while allowing you to focus on the resource definitions (TItem) and the core CRUD functionality. If you wish to implement one of these standard service types, you simply derive a class from the base class of interest and the corresponding service contract definition. Then you override the abstract methods to define the CRUD functionality for the resource in question, and then youre ready to host it. You dont have to worry about the HTTP details because they are handled by the base types. For example, suppose you want to implement a simple bookmark service using the ICollectionService<TItem> and CollectionServiceBase<TItem> types. You can do this by deriving a new class from both types while specifying Bookmark for the resource type. Then you override the handful of abstract methods defined on the base class including OnAddItem,
OnDeleteItem, OnGetItem, OnGetItems, and OnUpdateItem. Your method implementations define the CRUD functionality. Figure 9 shows a complete sample implementation for your reference.
VB C# C++ F# JScript
public class BookmarkService : CollectionServiceBase<Bookmark>, ICollectionService<Bookmark> { Dictionary<string, Bookmark> bookmarks = new Dictionary<string, Bookmark>(); protected override Bookmark OnAddItem(Bookmark initialValue, out string id) { id = Guid.NewGuid().ToString(); bookmarks.Add(id, initialValue); return initialValue; } protected override bool OnDeleteItem(string id) { bookmarks.Remove(id); return true; } protected override Bookmark OnGetItem(string id) { return bookmarks[id]; } protected override IEnumerable<KeyValuePair<string, Bookmark>> OnGetItems() { return bookmarks; } protected override Bookmark OnUpdateItem(string id, Bookmark newValue) { bookmarks[id] = newValue; return bookmarks[id]; } }
Figure 9: Sample Implementation using ICollectionService<TItem> and CollectionServiceBase<TItem> The sample implementation shown in Figure 9 is now completely ready to be hosted. In order to make the hosting aspect easier, the Microsoft.ServiceModel.Web.SpecializedServices namespace also contains a specialized host class for each specialized service type. For example, youll find SingletonServiceHost, CollectionServiceHost, and AtomPubServiceHost classes at your disposal. These specialized host types configure the necessary WCF behaviors for you behind the scenes so you dont have to worry about it. The following code sample illustrates how to host the BookmarkService implementation shown in Figure 9 within a simple console application:
VB C# C++ F# JScript
class Program { static void Main(string[] args) { CollectionServiceHost host = new CollectionServiceHost( typeof(BookmarkService), new Uri("http://localhost:8080/bookmarkservice")); host.Open(); Console.WriteLine("Host is up and running..."); Console.ReadLine(); host.Close(); } }
If you run this console application and then browse to the base address of the service, you should get the list of bookmarks back (returned by OnGetItems) as illustrated in Figure 10.
Figure 10: Browsing to BookmarkService while its Running And if you append /help to the end of the base URI, youll see the REST help page (see And if you append /help to the end of the base URI, youll see the REST help page (see Figure 11).).
Figure 11: Help Page Describing the Bookmark Service If you browse through the help page, youll see that this service implementation supports both XML and JSON message formats for each logical operation without any doing on our part. You can use these same techniques to implement singleton services (one that only exposes a single resource) or fully functional AtomPub services, which are becoming quite popular throughout the industry today. These specialized service types can make it much easier to get your RESTful service up and running, assuming it fits within the constraints imposed by the generic implementation.
In an effort to make these specialized types even easier for developers to use, the WCF REST Starter Kit also comes with a set of Visual Studio project templates that help bootstrap the process of using these specialized service types to create new service implementations.
Interface
Atom Feed WCF Service
Description
Produces a sample WCF service that shows how to programmatically generate and return a SyndicationFeed. You simply need to change the implementation to fill in the feed with your business data. Produces a complete skeleton implementation for a fully compliant AtomPub service, greatly reducing the amount of code you have to write for this scenario, and allowing you to focus primarily on how to map your business resources to the AtomPub protocol. Produces an XML over HTTP service that doesnt support the full HTTP interface. Instead, it provides simple GET and POST operations and makes it easy to build XMLbased services that arent truly RESTful.
REST Produces a service that exposes the full HTTP interface (GET, POST, PUT, and Collection WCF DELETE) around a collection of resources, and it provides both XML and JSON Service representations for the underlying resource. REST Singleton Produces a service that exposes the full HTTP interface (GET, POST, PUT, and
WCF Service
DELETE) around a singleton resource, and it provides both XML and JSON representations for the underlying resource.
Figure 14: Browsing to the generated singleton service (no changes) If you look at the source code within service.svc.cs, youll notice theyve provided a class definition for SampleItem this class represents the singleton resource exposed by the service implementation. The intention is for you to modify this class definition to represent the actual resource you wish to expose. This class is referenced elsewhere throughout the file so youll want to take advantage of Visual Studios refactoring support to propagate the change once youve made it. Heres what the initial class looks like:
VB
C# C++ F# JScript
// TODO: Modify the SampleItem. Use Visual Studio refactoring while modifying so // that the references are updated. /// <summary> /// Sample type for the singleton resource. /// By default all public properties are DataContract serializable /// </summary> public class SampleItem { public string Value { get; set; } }
And if you look at the service class definition, youll see it derives from SingletonServiceBase<SampleItem> and ISingletonService<SampleItem>. Now you need to modify the SampleItem class definition to something more appropriate. Since Im trying to expose my whereabouts, Ill change the class name to MyWhereabouts. And right when I do, Ill use the refactoring menu and select Rename SampleItem to MyWhereabouts (see Figure 15).
Figure 15: Using Visual Studio refactoring to change the resource class name Selecting this option takes care of renaming the class references throughout the rest of the file so everything should still build and run after the change. Now I can simply focus on modifying the class definition to model the resource representation Im trying to expose. For the MyWhereabouts resource, Ill simply add a few public fields called Placename, Timezone, Lattitude, and Longitude. Heres what my revised resource class looks like:
VB C# C++ F# JScript
public class MyWhereabouts { public string Placename { get; set; } public string Timezone { get; set; } public string Lattitude { get; set; } public string Longitude { get; set; } }
After making this change, I also modified the MyWhereabouts field initialization code to set these fields to my current location while writing this whitepaper:
VB C# C++ F# JScript
public class Service : SingletonServiceBase<MyWhereabouts>, ISingletonService<MyWhereabouts> { // TODO: This variable used by the sample implementation. Remove if needed MyWhereabouts item = new MyWhereabouts() { Placename = "Fruit Heights",
With these few changes in place, you can now press F5 again to browse to the service.svc file and you should see the <MyWhereabouts> resource displayed in the browser (see Figure 16).
Figure 16: Browsing to the MyWhereabouts Resource This generic service implementation supports the full HTTP interface (GET, POST, PUT, and DELETE) and each operation supports both XML and JSON representations. Simply add ?format=json to the end of the URI and youll retrieve the current resource in JSON format. You can now test the other operations (POST, PUT, and DELETE) by using Fiddler or by writing a custom client.
VB C# C++ F# JScript
public class Bookmark { public Uri Url { get; set; } public string User { get; set; } public string Title { get; set; } public string Tags { get; set; } public bool Public { get; set; } public DateTime LastModified { get; set; } }
With these changes in place, my new bookmark collection service is ready to test. Simply press F5 in Visual Studio and it will load the service and browse to the service.svc file. When the browser comes up, youll see an empty <ItemInfoList> element because the Bookmark collection is currently empty. At this point you can use something like Fiddler to add some bookmarks to the collection (via POST) or you can pre-populate the Bookmark items collection in the service constructor. Once youve populated the Bookmark collection, youll get some <Bookmark> elements back when you browse to the service again (see Figure 17). Notice the resulting list contains links to the individual Bookmark resources. You can browse to an individual bookmark by following one of the <EditLink> elements found within one of the <ItemInfo> elements. For example, you can get the first bookmark in the collection by browsing to http://localhost:26826/Service.svc/7b5b4a15-3b05-4f94-a7b81f324b5cfc7d (see Figure 18).
Figure 18: Browsing to a single bookmark within the collection At this point you can also use POST, PUT, and DELETE operations without any additional coding the generated project template already contains a default implementation for each one. You can POST new <Bookmark> elements to the services root address and it will generate a new Bookmark resource and assign it a new Id, and return a 201 Created response with the corresponding Location header. You can also PUT <Bookmark> elements to individual bookmark URIs to perform updates. And you can send DELETE requests to individual bookmark resources to remove them from the collection. As you can see, for this particular type of RESTful service (a collection-oriented service), the WCF REST Starter Kit made it possible to get our implementation up and running with very little coding on our part.
feed implementation like the one shown in Figure 19. This service will run as-is and produce a sample Atom feed that can be rendered in any standard Atom reader (see Figure 20 to see how its rendered in IE).
VB C# C++ F# JScript
// TODO: Please set IncludeExceptionDetailInFaults to false in production // environments [ServiceBehavior(IncludeExceptionDetailInFaults = true), AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed), ServiceContract] public partial class FeedService { // TODO: Modify the URI template and method parameters according to your // application. An example URL is http://<url-for-svc-file>?numItems=1 [WebHelp(Comment = "Sample description for GetFeed.")] [WebGet(UriTemplate = "?numItems={i}")] [OperationContract] public Atom10FeedFormatter GetFeed(int i) { SyndicationFeed feed; // TODO: Change the sample content feed creation logic here if (i < 0) throw new WebProtocolException(HttpStatusCode.BadRequest, "numItems cannot be negative", null); if (i == 0) i = 1; // Create the list of syndication items. These correspond to Atom entries List<SyndicationItem> items = new List<SyndicationItem>(); for (int j = 1; j <= i; ++j) { items.Add(new SyndicationItem() { // Every entry must have a stable unique URI id Id = String.Format(CultureInfo.InvariantCulture, "http://tempuri.org/Id{0}", j), Title = new TextSyndicationContent( String.Format("Sample item '{0}'", j)), // Every entry should include the last time it was updated LastUpdatedTime = new DateTime(
2008, 7, 1, 0, 0, 0, DateTimeKind.Utc), // The Atom spec requires an author for every entry. If the entry has // no author, use the empty string Authors = { new SyndicationPerson() { Name = "Sample Author" } }, // The content of an Atom entry can be text, xml, a link or arbitrary // content. In this sample text content is used. Content = new TextSyndicationContent("Sample content"), }); } // create the feed containing the syndication items. feed = new SyndicationFeed() { // The feed must have a unique stable URI id Id = "http://tempuri.org/FeedId", Title = new TextSyndicationContent("Sample feed"), Items = items }; feed.AddSelfLink( WebOperationContext.Current.IncomingRequest.GetRequestUri()); #region Sets response content-type for Atom feeds WebOperationContext.Current.OutgoingResponse.ContentType = ContentTypes.Atom; #endregion return feed.GetAtom10Formatter(); } }
Figure 20: Sample feed rendered in Internet Explorer This template simply provides sample code for generating a typical Atom feed service. You will need to modify the code to map your business entities into the SyndicationFeed instance, mapping each of the individual entities to a new SyndicationItem instance making use of the fields it provides.
AtomPub Services
When you want to implement a service that conforms to the Atom Publishing Protocol, you should use the Atom Publishing Protocol WCF Service project template that comes with the WCF REST Starter Kit. This template generates a complete AtomPub service that exposes a single sample collection. The generated service class derives from AtomPubServiceBase and IAtomPubService described earlier. You can test the service immediately by browsing to the service.svc file and the service will return an AtomPub service document describing the collections it supports (see Figure 21). As you can see, this service exposes a collection called Sample Collection that you can access by adding collection1 to the end of the services root URL. When you access the collection, the service returns an Atom feed representing the sample collection (see Figure 22). The service also supports adding, updating, and deleting Atom entries through the standard AtomPub HTTP interface. When you build AtomPub services using the WCF REST Starter Kit, your job is to focus on the logical collections you want to expose. Youll need to define a mapping between your business entity collections and AtomPub collections exposed by the service, which essentially boils down to defining a mapping between your custom business entity classes and the WCF SyndicationFeed/Item classes.
Figure 22: Browsing to the sample collection exposed by the AtomPub service
VB C#
C++ F# JScript
[ServiceBehavior(IncludeExceptionDetailInFaults = true), AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed), ServiceContract] public partial class Service { [WebHelp(Comment = "Sample description for GetData")] [WebGet(UriTemplate = "GetData?param1={i}¶m2={s}")] [OperationContract] public SampleResponseBody GetData(int i, string s) { // TODO: Change the sample implementation here if (i < 0) throw new WebProtocolException(HttpStatusCode.BadRequest, "param1 cannot be negative", null); return new SampleResponseBody() { Value = String.Format("Sample GetData response: '{0}', '{1}'", i, s) }; } [WebHelp(Comment = "Sample description for DoWork")] [WebInvoke(UriTemplate = "DoWork")] [OperationContract] public SampleResponseBody DoWork(SampleRequestBody request) { //TODO: Change the sample implementation here return new SampleResponseBody() { Value = String.Format("Sample DoWork response: '{0}'", request.Data) }; } }
Since REST services are simply HTTP-based services, you can literally use any HTTP API to consume them. This gives you a great deal of flexibility on the client-side. Microsoft .NET provides the System.Net classes, such as WebRequest and WebResponse, for programming HTTP client code. These classes will get the job done but they do make the client-side experience feel more complex than it should be. Developers used to working with SOAP-based proxies usually dont find it very appealing or natural. In an effort to simplify the client-side programming experience for consuming RESTful services, the WCF REST Starter Kit (Preview 2) comes with a new HTTP API called HttpClient that provides a more natural model for programming the uniform HTTP interface along with numerous extension methods that make it easier to handle a variety of different content types found within the HTTP messages.
VB C# C++ F# JScript
public class HttpClient : IDisposable { public HttpClient(); public HttpClient(string baseAddress); public HttpClient(Uri baseAddress); public Uri BaseAddress { get; set; } public RequestHeaders DefaultHeaders { get; set; } public IList<HttpStage> Stages { get; set; } public HttpWebRequestTransportSettings TransportSettings { get; set; } public event EventHandler<SendCompletedEventArgs> SendCompleted; public IAsyncResult BeginSend(HttpRequestMessage request, AsyncCallback callback, object state); protected virtual HttpStage CreateTransportStage(); public void Dispose(); protected virtual void Dispose(bool disposing); public HttpResponseMessage EndSend(IAsyncResult result); public HttpResponseMessage Send(HttpMethod method); public HttpResponseMessage Send(HttpRequestMessage request); public HttpResponseMessage Send(HttpMethod method, string uri); public HttpResponseMessage Send(HttpMethod method, Uri uri); public HttpResponseMessage Send(HttpMethod method, string uri, HttpContent content); public HttpResponseMessage Send(HttpMethod method, string uri, RequestHeaders headers); public HttpResponseMessage Send(HttpMethod method, Uri uri, HttpContent content); public HttpResponseMessage Send(HttpMethod method, Uri uri, RequestHeaders headers); public HttpResponseMessage Send(HttpMethod method, string uri, RequestHeaders headers, HttpContent content); public HttpResponseMessage Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content); public void SendAsync(HttpRequestMessage request); public void SendAsync(HttpRequestMessage request, object userState); public void SendAsyncCancel(object userState); protected void ThrowIfDisposed(); } public static class HttpMethodExtensions { public static HttpResponseMessage Delete(this HttpClient client, string uri); public static HttpResponseMessage Delete(this HttpClient client, Uri uri); public static HttpResponseMessage Get(this HttpClient client); public static HttpResponseMessage Get(this HttpClient client, string uri); public static HttpResponseMessage Get(this HttpClient client, Uri uri); public static HttpResponseMessage Get(this HttpClient client, Uri uri, HttpQueryString queryString); public static HttpResponseMessage Get(this HttpClient client, Uri uri, IEnumerable<KeyValuePair<string, string>> queryString); public static HttpResponseMessage Head(this HttpClient client, string uri); public static HttpResponseMessage Head(this HttpClient client, Uri uri);
public static HttpResponseMessage Post(this HttpClient client, string uri, HttpContent body); public static HttpResponseMessage Post(this HttpClient client, Uri uri, HttpContent body); public static HttpResponseMessage Post(this HttpClient client, string uri, string contentType, HttpContent body); public static HttpResponseMessage Post(this HttpClient client, Uri uri, string contentType, HttpContent body); public static HttpResponseMessage Put(this HttpClient client, string uri, HttpContent body); public static HttpResponseMessage Put(this HttpClient client, Uri uri, HttpContent body); public static HttpResponseMessage Put(this HttpClient client, string uri, string contentType, HttpContent body); public static HttpResponseMessage Put(this HttpClient client, Uri uri, string contentType, HttpContent body); }
Figure 24: HttpClient and HttpMethodExtensions class definitions Lets take a look at an example to see how HttpClient simplifies things. Well consume a real RESTful service found on the Web that wasnt built with .NET. Well consume the Twitter REST API. If you browse to the Twitter REST API documentation at http://apiwiki.twitter.com/Twitter-APIDocumentation, you can quickly learn how to begin issuing the proper HTTP requests to integrate with the service. The following code shows how to a retrieve a Twitter users friend timeline:
VB C# C++ F# JScript
HttpClient http = new HttpClient("http://twitter.com/statuses/"); http.TransportSettings.Credentials = new NetworkCredential("{username}", "{password}"); HttpResponseMessage resp = http.Get("friends_timeline.xml"); resp.EnsureStatusIsSuccessful(); ProcessStatuses(resp.Content.ReadAsStream());
When we construct the HttpClient instance, we provide the base address for the Twitter REST API service and then we provide the users HTTP credentials through the TransportSettings.Credentials property. Now were ready to use the various Get, Post, Put, and Delete methods to interact with the different resources exposed by the service. In this example, Im calling Get to retrieve the friends_timeline.xml resource from the service. Once that returns, I can call EnsureStatusIsSuccessful on the resp object to make sure we got a 200-level HTTP status code back. Next, we need to process the contents of the response message. One way to accomplish that is to read the response out as a stream and then process the stream (ReadAsStream) with your favorite XML API. Heres an example that shows how to process the response XML using XmlDocument:
VB C# C++ F# JScript
static void ProcessStatuses(Stream str) { XmlDocument doc = new XmlDocument(); doc.Load(str); XmlNodeList statuses = doc.SelectNodes("/statuses/status"); foreach (XmlNode n in statuses) Console.WriteLine("{0}: {1}", n.SelectSingleNode("user/screen_name").InnerText, n.SelectSingleNode("text").InnerText); }
The HttpClient class comes with functionality for processing the message content as a stream, a string, or a byte array. In addition to this basic functionality, the WCF REST Start Kit (Preview 2) comes with another assembly called Microsoft.Http.Extensions that contains numerous extension methods that make it possible to process the message content using other popular techniques (XLinq, XmlSerializer, SyndicationFeed, etc). Well see how these extension methods work in the following section.
Lets look at another example showing how to update a users Twitter status. You can accomplish this with HttpClient using the following code (assuming HttpClient is already instantiated above):
VB C# C++ F# JScript
HttpUrlEncodedForm form = new HttpUrlEncodedForm(); form.Add("status", "my first HttpClient app"); resp = http.Post("update.xml", form.CreateHttpContent()); resp.EnsureStatusIsSuccessful();
The update.xml resource requires a POST request and it expects the message to contain a URL-encoded string containing the new status text. HttpClient makes it easy to generate a URLencoded message via the HttpUrlEncodedForm class, and then you simply call Post supplying the content. This quick example illustrates how easy is to issue GET and POST requests using HttpClient. In the following sections, well dive deeper into the HttpClient details and highlight some of its key features.
Extension Method
ReadAsDataContract ReadAsJsonDataContract ReadAsServiceDocument ReadAsSyndicationFeed ReadAsXmlReader ReadAsXElement ReadAsXmlSerializable Figure 25: HttpContent Extension Methods
Namespace
System.Runtime.Serialization System.Runtime.Serialization.Json System.ServiceModel.Syndication System.ServiceModel.Syndication System.Xml System.Xml.Linq System.Xml.Serialization
Lets look at a few examples that show how to use some of these extension methods. Well start with an XLinq example since its a common .NET XML programming choice today. Instead of calling ReadAsStream on the Content property, well now call ReadAsXElement as illustrated here:
VB C# C++ F# JScript
Remember, youll need a reference to the Microsoft.Http.Extensions assembly and youll need to add a using statement to the file for System.Xml.Linq assuming youve done both of these steps, you should see ReadAsXElement within intellisense on the Content property. The following example illustrates how we can process the message content as an XElement:
VB C# C++ F# JScript
static void ProcessStatusesAsXElement(XElement root) { var statuses = root.Descendants("status"); foreach (XElement status in statuses) Console.WriteLine("{0}: {1}", status.Element("user").Element("screen_name").Value, status.Element("text")); }
It would be very similar if you wanted to process the message content using XmlReader instead of XElement youd simply call ReadAsXmlReader and process the content accordingly. Instead of using XML APIs directly, many developers prefer to take advantage of XML serialization techniques, which allows them to work with strongly-typed .NET types instead of generic XML nodes. The ReadAsDataContract and ReadAsJsonDataContract extension methods allow you to leverage the DataContractSerializer (for XML or JSON content respectively) for serialization while ReadAsXmlSerializable allows you to leverage the XmlSerializer serialization engine. However, before you can use any of these serialization-based methods, youll need to acquire some .NET classes that appropriately model the message content youre going to process. It may be possible to generate the appropriate classes from an XML Schema definition supplied by the service or from some sample XML that you can retrieve while actually using the service during development. But if all else fails, you can always author these types manually based on your knowledge of the XML format. For example, here are some C# classes that model the statuses were getting back from Twitter above when using the DataContractSerializer to perform the deserialization:
VB C# C++ F# JScript
[assembly: ContractNamespace("", ClrNamespace = "TwitterShell")] [CollectionDataContract(Name = "statuses", ItemName = "status")] public class statusList : List<status> { } public class user { public string id; public string name; public string screen_name; } public class status { public string id; public string text; public user user; }
With these classes in place, we can now use the ReadAsDataContract method specifying the root type to use during the deserialization process (in this case, statusList):
VB C# C++ F# JScript
Now that we have the message content deserialized into a statusList object, the processing code becomes much simpler as you can see here:
VB C# C++ F# JScript
static void ProcessStatusesAsDataContract(statusList list) { foreach (status status in list) Console.WriteLine("{0}: {1}", status.user.screen_name, status.text); }
If the HTTP response will be returned in JSON format (instead of XML), you can simply call ReadAsJsonDataContract as illustrated here:
VB C# C++ F# JScript
The rest of the processing code remains the same. Additionally, if you want to use the XmlSerializer engine, youll first need to ensure that you have serializable types that are compatible with the XmlSerializer-mapping. For this particular example, wed need to replace the statusList type with the following root type (because the XML mapping is different):
VB C# C++ F# JScript
Then you simply call ReadAsXmlSerializable instead of ReadAsDataContract, specifying statuses for the root type to deserialize. In general, XmlSerializer is more flexible than DataContractSerializer in terms of the XML its able to handle. Hence, its likely that XmlSerializer will become a more common choice for consuming RESTful services. Plus, the WCF REST Starter Kit (Preview 2) comes with a Visual Studio plug-in that makes generating XmlSerializer types easy. Well cover how it works in the following section. As a final example, what if the service returns an Atom feed? In this case, you can simply call ReadAsSyndicationFeed and then youll get back a SyndicationFeed object to process:
VB C# C++ F# JScript
Then you can process the SyndicationFeed object to extract the information of interest (youll need to know where the information is located within the Atom feed structure):
VB C# C++ F# JScript
static void ProcessStatusesAsFeed(SyndicationFeed feed) { foreach (SyndicationItem item in feed.Items) Console.WriteLine("{0}: {1}", item.Authors[0].Name, item.Title.Text); }
As you can see, the new HttpClient class makes it really easy to consume RESTful services in .NET. The new extension methods found in Microsoft.Http.Extensions provide a great deal of flexibility around message processing and simplify some of the most common REST scenarios (XML, JSON, and Atom, etc).
data, or through a variety of other formats that you can use within the HTTP request entity body (e.g., XML, JSON, Atom, etc). If the service requires query string input, you can use the HttpQueryString class build it properly. The following example shows how to build a query string that we can supply to the Get method:
VB C# C++ F# JScript
HttpQueryString vars = new HttpQueryString(); vars.Add("id", screenname); vars.Add("count", count); resp = http.Get(new Uri("user_timeline.xml", UriKind.Relative), vars); resp.EnsureStatusIsSuccessful(); DisplayTwitterStatuses(resp.Content.ReadAsXElement());
If the service requires URL-encoded form input (e.g., what youd get from an HTML <form> submission), you can use the HttpUrlEncodedForm or HttpMultipartMimeForm class to build the proper content (use the later if you need to produce a multi-part MIME form). The following example illustrates how to build a simple form submission that we can supply to the Post method:
VB C# C++ F# JScript
HttpUrlEncodedForm form = new HttpUrlEncodedForm(); form.Add("status", status); resp = http.Post("update.xml", form.CreateHttpContent()); resp.EnsureStatusIsSuccessful(); Console.WriteLine("Status updated!");
In addition to these classes, the Microsoft.Http.Extensions assembly comes with some additional extension methods that simplify the process of generating HttpContent objects that you can supply to HttpClient as input. These methods are defined in the HttpContentExtensions class and include things like Create (from an XElement), CreateDataContract, CreateJsonDataContract, CreateXmlSerializable, CreateAtom10SyndicationFeed, and CreateRss20SyndicationFeed. Youll want to use these methods when you need to generate one of these types of content for the HTTP request message.
VB C# C++ F# JScript
HttpResponseMessage resp = http.Get("public_timeline.atom"); resp.EnsureStatusIsSuccessful(); ProcessStatusesAsFeed(resp.Content.ReadAsSyndicationFeed()); DateTime? lastAccessDate = resp.Headers.Date; ... http.DefaultHeaders.IfModifiedSince = lastAccessDate; resp = http.Get("public_timeline.atom"); Console.WriteLine("status={0}", resp.StatusCode);
These strongly-typed HTTP header classes make it easier to work with the HTTP headers in your code because they shield you from many aspects of the underlying HTTP protocol details.
VB C# C++
F# JScript
public class MyHttpStage : HttpProcessingStage { public override void ProcessRequest(HttpRequestMessage request) { Console.WriteLine("ProcessRequest called: {0} {1}", request.Method, request.Uri); } public override void ProcessResponse(HttpResponseMessage response) { Console.WriteLine("ProcessResponse called: {0}", response.StatusCode); } }
Once youve implemented your custom HttpStage-derived class, you can take advantage of it while using HttpClient. The following example illustrates how you can add a MyHttpStage instance into the mix before issuing any HTTP requests:
VB C# C++ F# JScript
HttpClient http = new HttpClient("http://twitter.com/statuses/"); http.TransportSettings.Credentials = new NetworkCredential("skonnarddemo", "baby95"); // configure the custom stage http.Stages.Add(new MyHttpStage()); HttpResponseMessage resp = http.Get("public_timeline.atom");
Now, when you call the Get method, youll see the MyHttpStage messages printed to the console window before and after issuing the HTTP request to the target service. You can use this
interception technique to implement a variety of client-side HTTP processing needs (e.g., security, logging, tracing, custom caching, etc) in a way that fosters more reusability across HTTP client applications.
VB C# C++ F# JScript
public class AtomPubClient : HttpClient { public AtomPubClient(); public SyndicationItem AddEntry(SyndicationFeed feed, SyndicationItem newEntry); public SyndicationItem AddEntry(Uri feedUri, SyndicationItem newEntry); public SyndicationItem AddMediaResource(SyndicationFeed feed, string contentType, string description, HttpContent mediaContent); public SyndicationItem AddMediaResource(Uri mediaCollectionUri, string contentType, string description, HttpContent mediaContent); public void DeleteEntry(SyndicationItem entry); public void DeleteEntry(Uri itemUri); public SyndicationItem GetEntry(Uri itemUri); public SyndicationFeed GetFeed(Uri feedUri); public ServiceDocument GetServiceDocument(Uri serviceDocumentUri); public SyndicationItem UpdateEntry(SyndicationItem oldValue, SyndicationItem newValue);
Notice how it provides methods like AddEntry, GetEntry, UpdateEntry, GetFeed, etc that are specific to an AtomPub service, which is a much more natural way to think about interacting with those types of services than using the underlying Get, Post, Put, and Delete methods on HttpClient. The following code example illustrates how to use the AtomPubClient class to navigate an AtomPub service and add a new Atom entry into the first workspace collection:
VB C# C++ F# JScript
AtomPubClient client = new AtomPubClient(); ServiceDocument doc = client.GetServiceDocument( new Uri("http://localhost:30807/Service.svc/")); Uri feedUri = doc.Workspaces[0].Collections[0].Link; SyndicationFeed feed = client.GetFeed(feedUri); SyndicationItem item = new SyndicationItem() { Title = new TextSyndicationContent("New Item"), PublishDate = DateTime.Now }; client.AddEntry(feed, item);
The WCF REST Starter Kit (Preview 2) also comes with a class called PollingAgent that makes it easier to implement client logic for polling a service resource and only doing something when the resource changes. You use PollingAgent in conjunction with an HttpClient object that actually performs the HTTP work. Heres the complete class definition for PollingAgent:
VB C# C++ F# JScript
public class PollingAgent : IDisposable { public PollingAgent(); public HttpClient HttpClient { get; set; } public bool IgnoreExpiresHeader { get; set; } public bool IgnoreNonOKStatusCodes { get; set; } public bool IgnoreSendErrors { get; set; } public TimeSpan PollingInterval { get; set; } public event EventHandler<ConditionalGetEventArgs> ResourceChanged; public void Dispose(); public void StartPolling(); public void StartPolling(Uri uri); public void StartPolling(Uri uri, EntityTag etag, DateTime? lastModifiedTime); public void StopPolling(); }
So you create an instance of the PollingAgent class and provide it with an HttpClient object to use. Then you establish the callback method for the ResourceChanged event and specify the polling interval. Once you have all that in place, you simply call StartPolling and supply the target resource URI. The following code sample illustrates how to set this up for polling the Twitter public timeline:
VB C# C++ F# JScript
class Program {
static void Main(string[] args) { PollingAgent pollingClient = new PollingAgent(); pollingClient.HttpClient = new HttpClient(); pollingClient.HttpClient.TransportSettings.Credentials = new NetworkCredential("skonnarddemo", "baby95"); pollingClient.PollingInterval = TimeSpan.FromSeconds(10); pollingClient.ResourceChanged += new EventHandler<ConditionalGetEventArgs>( pollingClient_ResourceChanged); pollingClient.StartPolling( new Uri("http://twitter.com/statuses/public_timeline.xml")); Console.WriteLine("polling..."); Console.ReadLine(); } static void pollingClient_ResourceChanged(object s, ConditionalGetEventArgs e) { ProcessStatusesAsXElement(e.Response.Content.ReadAsXElement()); } static void ProcessStatusesAsXElement(XElement root) { var statuses = root.Descendants("status"); foreach (XElement status in statuses) Console.WriteLine("{0}: {1}", status.Element("user").Element("screen_name").Value, status.Element("text")); } }
As you can see from these examples, HttpClient provides a simple HTTP foundation that you can extend to provide more specialized client-side programming models. Investing some time in building your own HttpClient-derived classes pays big dividends in terms of the client-side developer experience.
Conclusion
Microsoft is striving hard to provide a first-class programming model for both implementing and consuming RESTful services using the Microsoft .NET framework. WCF 3.5 introduced the fundamental Web programming model required to build RESTful services but it was only a start. The WCF REST Starter Kit is a Microsoft-sponsored CodePlex project that provides a set of WCF extensions and key Visual Studio integration designed specifically to simplify RESTfocused development tasks. Many of the features found in the WCF REST Starter Kit today will most likely find their way into future versions of the .NET framework, but theres no reason to wait, you can begin putting these features to use today.
A Guide to Designing and Building RESTful Web Services with WCF 3.5
Aaron Skonnard, Pluralsight October 2008
Overview
From the point of view of REST, a real Web service is a service designed to embrace the Web from the ground up. The Web has become the most successful distributed computing platform ever developed, thanks to years of investment and widespread usage. The Web platform includes concepts that youre probably already familiar with like URIs, HTTP, and common data formats like XML, RSS/ATOM, and JSON. Ultimately, services that embrace these core concepts will immediately derive the valuable benefits they provide. REST defines an architectural style based on a set of constraints for building things the Web way. REST is not tied to any particular technology or platform its simply a way to design things to work like the Web. People often refer to services that follow this philosophy as RESTful services. In this whitepaper, well cover the fundamental REST design principles and show you how to build RESTful services with Windows Communication Foundation (WCF), the WCF REST Starter Kit, and ADO.NET Data Services.
Resource-Oriented Architecture
On the Web, every resource is given a unique identifier, also known as a universal resource identifier (URI). The most common type of URI used on the Web today is a uniform resource locator (URL). As an example, the URL http://www.pluralsight.com/main/ilt/schedule.aspx identifies and locates Pluralsights upcoming training course schedule, a popular resource made available on our site.
Since a given URI uniquely identifies a resource, it can be saved for future use and shared with others. For example, when you find a resource you want to get back to later, you can: try to remember it, write it down on a napkin, save it to disk (as a browser bookmark), or store it in a database of bookmarks on the Web, in which case the bookmark itself becomes a new Web resource. You can also share the resource with others by telling them the URI or emailing it to them so they can easily browse to it themselves. Many companies try hard to create easy-toremember URIs that can be successfully conveyed via advertising and will hopefully spread via word-of-mouth. In the end, as long as you have the URI, you can enter it into a Web browser and retrieve the resource at some future point in time. Now, the reason its called the Web is because resources can contain hyperlinks to other resources, thereby creating a Web of resources. Hyperlinks make it possible to navigate from one resource to another by using the target resource URI. For example, in HTML you link to another resource through the anchor element. When a browser renders an anchor element, it provides a visual cue showing that you can click on the anchor text to issue a GET request for the target resource URI. Humans play an important role in most Web applications because theyre the ones viewing the page, entering data in forms, and clicking links. Humans are really the client-side engine navigating the Web of resources. When you retrieve a resource using a Web browser, youre really retrieving a representation of that resource. This implies that there could be multiple representations of a particular resource. There are many standard and common formats used on the Web today to represent resources that virtually all browsers understand. One of the most common formats is (X)HTML but others are common as well, including JPEG and GIF, WMV and SWF, RSS and ATOM, CSS and JavaScript/JSON to name a few. When a browser receives one of these representations, it does its best to render it for human viewing.
be creating a new course description resource. And, of course, youd delete a course description by issuing a DELETE request. Figure 1: Some common HTTP methods
Method
GET PUT DELETE POST HEAD OPTIONS
Description
Requests a specific representation of a resource Create or update a resource with the supplied representation Deletes the specified resource Submits data to be processed by the identified resource Similar to GET but only retrieves headers and not the body Returns the methods supported by the identified resource
Safe Idempotent
Yes No No No Yes Yes Yes Yes Yes No Yes Yes
Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval. HTML 5, which is currently under development, plans to fix this by adding new support for PUT and DELETE. GET, HEAD, and OPTIONS are all examples of safe methods that arent intended to have side effects. All safe methods are also idempotent, as are PUT and DELETE, so you should be able to repeat them multiple times without harm. The POST method is something of a special case. According to the HTTP specification, POST should be used to provide a representation that can be treated as a subordinate of the target resource. For example, you could POST a new blog entry to the URI representing the blog feed, causing a new blog entry to be added to the feed. POST can also be used to process a block of data such as the data transmitted by an HTML form. The actual function performed by the POST method is defined by the server. Therefore, POST cannot be considered safe or idempotent by clients. HTTP also defines a suite of standard status codes that specify the result of processing the request. Status codes are organized into ranges that mean different things. For example, status codes in the 200 range mean successful while status codes in the 400 range mean the client issued a bad request. Figure 2 describes each status code range and provides a few examples of common status codes. Figure 2: Some common HTTP status codes
Status Range
100
Description
Informational
Examples
100 Continue
200 201 202 300 304 400 402 404 405 500 501
Successful Created Accepted Redirection Not Modified Client error Payment Required Not Found Method Not Allowed Server error Not Implemented
200 OK
401 Unauthorized
The HTTP specification also defines a suite of headers that can be used to negotiate behavior between HTTP clients and servers. These headers provide built-in solutions for important communication concepts like redirection, content negotiation, security (authentication and authorization), caching, and compression. When you build something using HTTP, you get these solutions for free and dont have to invest time in reinventing similar solutions in your own code. And when youre not using HTTP, its likely that youll end up developing similar solutions for these things when your system grows in scale. The Web platform has been around for years and countless organizations have deployed successful large-scale distributed applications using the concepts I just described. The Webs general architectural style has been concretely described in a PhD dissertation as whats known as REST.
REST Defined
While REST seems to be growing in popularity these days, its a term that seems to mean different things to different people. The official definition for REST is defined in Chapter 5 of Roy Fieldings PhD dissertation entitled Architectural Styles and the Design of Network -based Software Architectures. Roy Fielding was one of the authors of the URI and HTTP specifications, which sit at the heart of the Web. Chapter 5 of his dissertation, entitled Representational State Transfer (REST), attempts to codify the architectural style and design constraints that make the Web what it is.
REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance. However, the key design constraint that sets REST apart from other distributed architectural styles is its emphasis on a uniform interface between components. The theory is that generalizing and standardizing the component interface will ultimately simplify the overall system architecture and provide more visibility into the various interactions. REST further defines how to use the uniform interface through additional constraints around how to identify resources, how to manipulate resources through representations, and how to include metadata that make messages self-describing. When something conforms to these REST design constraints, we commonly refer to it as RESTful a term that I casually use throughout this whitepaper. The Web is indeed RESTful. The Web was built on HTTPs uniform interface (the methods described in Figure 1) and the focus is on interacting with resources and their representations. Although in theory REST isnt tied to any specific platform or technology, the Web is the only major platform that fully embodies REST today. So, in practical terms, if youre going to build something thats RESTful today, youll probably do it on the Web using HTTP.
Uniform Interface
Some argue that generalizing the component interface limits the capabilities of the system, but this is simply not true. There is great power in the simplicity of a uniform interface because of the value it adds at larger scales. The REST model is Turing-complete and can be used to implement complex systems. A comparison might help explain how this is possible lets consider the popular LEGO building blocks as an example. If youve played with LEGO products before, you know there are only a few ways to connect them together, which represents the LEGO uniform interface. All LEGO products, regardless of when or where you buy them, can connect with one another through its uniform interface. When new LEGO products are released, they can be incorporated into existing LEGO systems and the user doesnt have to learn anything new. The new components work just like all other LEGO products. You might wonder if the limited number of connection possibilities will constrain what youre able to build with LEGO products. But if youve ever been to LEGOLAND, youll know it doesnt. Youll find some incredibly complex objects at LEGOLAND including replicas of cars, buildings, even dinosaurs which were all built from a variety of LEGO products, connected through the LEGO uniform interface. HTTP defines a similar model for the Web. The various methods defined by the HTTP specification (see Figure 1) provide a uniform interface for interacting with resources on the Web. All Web browsers, servers, intermediaries, and custom applications understand this uniform interface and the semantics of each operation. This allows them to connect to one
another and exchange information without issues, despite platform and technology differences. And new Web components can be added at any time without causing disruption or requiring changes to the other components already in existence. The idea of a uniform interface is often hard to accept for many developers, especially those who are used to working with RPC-based component technologies. With RPC, every new component introduces a new interface a new set of methods for accessing the components functionality. Hence, the component developer is focused on designing and implementing methods, and therefore, new application protocols. Its been this way for years, and few technologies move away from this trend. Before clients can take advantage of a new component, they must learn the intricacies of the new interface (application protocol) and the semantics of each operation. Ultimately, as the number of interfaces increases, so does the overall complexity of the system. This complexity can become unwieldy to manage over time and often leads to brittle systems that cant cope with versioning and change. A system built around a uniform interface for communication provides stability because it rarely changes and there are only a few methods for everyone to learn. Applications using a uniform interface are free to change at any time while the communication methods connecting them remain stable over time. This is how the Web has always worked, and one of the primary reasons it has worked so well.
RESTful Services
The move towards RESTful services is ultimately about moving towards a programmable Web, one where we can replace humans with application code. Its essentially about applying the principles of REST to the domain of Web services. Ultimately, designing RESTful services is no different than designing RESTful Web applications except we need to facilitate removing humans from the equation. When you design a RESTful service, you have to think about things differently. You no longer focus on designing methods. Instead, you focus on the resources that make up your system, their URIs, and their representations. RESTful services conform to the HTTP uniform interface you simply need to decide which of those methods youll support for each resource. In order to remove humans from the equation, youll need to use resource representations that are easy to programmatically consume. Unlike traditional RPC-style frameworks that attempt to hide communication details, RESTful services actually embrace HTTP and its features and fully take advantage of them as much as possible. As a result, RESTful services automatically receive the valuable benefits inherent in the Web platform including the built-in security features, caching controls, compression, and ultimately improved performance and scalability. And best of all, you dont have to wait for it the Web platform is ready today complete with products, infrastructure, and helpful resources available for immediate use.
Operation
createUserAccount getUserAccount updateUserAccount deleteUserAccount getUserProfile createBookmark updateBookmark deleteBookmark getBookmark
Description
Creates a new user account Retrieves user account details for the authenticated user Updates user account details for the authenticated user Deletes the authenticated users account Retrieves a specific users public profile information Creates a new bookmark for the authenticated user Updates an existing bookmark for the authenticated user Deletes one of the authenticated users bookmarks Retrieves a specific bookmark (anyone can retrieve a public bookmark; only authenticated users can retrieve a private bookmark) Retrieves the users private bookmarks, allows filtering by tags
getUserBookmarks
getUserPublicBookmarks Retrieves the users public bookmarks, allows filtering by tags getPublicBookmarks Retrieves all public bookmarks, allows filtering by tags
Several of these operations are publicly accessible including createUserAccount, getUserProfile, getUserPublicBookmarks, getPublicBookmarks, and getBookmark (assuming the bookmark is public). Anyone can use these operations without authentication. The remaining operations, however, require the user to provide valid credentials and can be used only by valid, authenticated users. For example, only an authenticated user can modify or delete his account or create, update, and delete bookmarks. Also, bookmarks can be marked as public or private and they can be labeled with arbitrary textual tags. Anyone can retrieve public bookmarks, but only authenticated users can access private bookmarks. Plus, all of the operations that return bookmark collections can be filtered by tags.
However, we need to get a little more specific than this since well need the ability to operate on individual bookmarks as well as different collections of bookmarks. After analyzing the current functionality, its apparent well need the ability to address the following types of resources:
An individual user account A specific users public profile An individual bookmark A users collection of private bookmarks A users collection of public bookmarks The collection of all public bookmarks
You can think of these things as the nouns that make up the service. The original service design outlined in Figure 3 focused on verbs and not the underlying nouns. This is where RESTful design takes a radical turn. With REST, you focus first on the nouns first (e.g., the resources) because youll rely on a standard set of verbs (the uniform interface) to operate on them within the service.
bookmarks can get quite large, we should probably also provide a way to filter the collection of bookmarks somehow. We can accomplish this by building additional scoping information into the URI design. For example, we can use the following query string to identify all public bookmarks marked with a particular tag:
?tag={tag}
In this case, the tag is providing additional scoping information that consumers can use to reduce the identified collections size. The syntax Im using here is referred to as URI template syntax. Anything within curly braces represents a variable, like tag in this case. Everything else in the URI (not enclosed within curly braces) is considered a static part of the URI. Later, when we implement the service, youll see how to map these URI variables to method parameters in our WCF code. The URI template in this case is relative to the services base URI. So you can identify all public bookmarks marked with the rest tag using http://contoso.com/bookmarkservice?tag=rest. We can further filter the list of public bookmarks by username. In this case, well use the username as part of the path to filter the collection by user before applying the tag scoping information:
{username}?tag={tag}
For example, you can identify all of skonnards bookmarks marked with wcf using http://contoso.com/bookmarkservice/skonnard?tag=wcf. And you can access all of onions bookmarks marked with silverlight using http://contoso.com/bookmarkservice/onion?tag=silverlight. Next, lets think about how to identify a particular user. Since weve already used a variable in the first path segment (for identifying a users public bookmarks), well need to specify a literal string in that first segment to change the meaning of what comes next. For example, we can say that all URIs starting with users will identify a specific user. Well use the following templates to identify the user resources:
/users/{username} /users/{username}/profile
And we can identify a users complete list of bookmarks by adding bookmarks instead:
/users/{username}/bookmarks
Plus, like before, we can filter bookmarks by using tag scoping information:
/users/{username}/bookmarks?tag={tag}
When it comes to identifying individual bookmarks, we have to make a decision about how to do that. If we assign each bookmark a unique Id, we could potentially use a simpler URI template for identifying individual bookmarks based on the Id. However, since bookmarks really belong to a specific user, it might make sense to make individual bookmark identifiers relative to a particular user as shown here:
/users/{username}/bookmarks/{id}
Figure 4 summarizes the URI design for our RESTful bookmark service. Now that we know what resources were dealing with and how to identify them, we can turn our attention to thinking about which methods on the uniform interface well support for each of these resources. Figure 4: The BookmarkService URI design
Operation
A collection of all public bookmarks A users collection of public bookmarks An individual user account A specific users public profile A users collection of bookmarks An individual bookmark
Description
?tag={tag} {username}?tag={tag} users/{username} users/{username}/profile users/{username}/bookmarks?tag={tag} users/{username}/bookmarks/{id}
client will provide a user account representation in the HTTP request body containing the users information. Once created, a user can retrieve her account resource by issuing a GET request to her account URI. She can issue a PUT request to update her account resource by supplying an updated user account representation. She can also issue a DELETE request (with no representation) to delete her account. When these operations are successful, the service returns a 200 (OK) response. If the client attempts to update or delete a non-existent account, the service will return a 404 (Not Found) response. For individual bookmark resources, well support GET, POST, PUT, and DELETE requests. If a particular bookmark is marked as private, only the owner can retrieve it, but if its public, anyone can retrieve it. When a user creates a new bookmark, the service is responsible for assigning it a unique bookmark Id. Hence, the client wont know the Id to use in the URI ahead of time. So, instead of using a PUT request, well have users POST bookmarks to the users bookmark collection resource. The handler for the POST request will create the new bookmark, assign it an Id, and return a 201 (Created) to the client, specifying the URI of the new bookmark resource in the Location header. This explains when to use POST or PUT for creating new resources. The answer ultimately lies in who is responsible for determining the new resources URI. If the client is in charge, the client can use PUT to the new URI (like we did for user accounts) and the service can return a response code of 201 (Created). However, if the service is in charge of generating the new URI, the client should POST the new resource to a factory URI like weve done for bookmarks. Then, the service can return a response code of 201 (Created) along with the URI of the new resource in the response Location header. Once clients know the bookmark IDs, they can issue PUT and DELETE requests to individual bookmark URIs to update and delete bookmarks. If successful, the service will return a 200 (OK). If the client uses a URI that doesnt exist, the service will return a 404 (Not Found) response. Figure 5 summarizes the final design of our RESTful interface for bookmark resources, showing which HTTP methods well support with each resource. Weve been able to completely replace the functionality found in the original RPC service through HTTPs uniform interface. Figure 5: RESTful interface for user accounts
Method
PUT GET PUT
URI Template
users/{username} users/{username} users/{username}
Security Considerations
Our service requires the ability to authenticate users so we can authorize the resources and methods theyre allowed to access. For example, only authenticated users can access their own user account resources and operate on them. And only authenticated users can create new bookmarks and operate on them. If an unauthenticated user attempts to do so or a user attempts to operate on another users resources the service needs to return a 401 (Unauthorized) response and deny access. So we need to figure out how well identify users in order to authenticate them. HTTP comes with some built-in authentication mechanisms, the most popular of which is basic access authentication. This is one of the most popular authentication schemes used on the Web today because its so easy and widely supported, but its also one of the most unsecure, because passwords are sent across the wire in a simple-to-decode plain text format. One way around this is to require SSL (HTTPS) for all HTTP traffic that will be using basic authentication, thereby encrypting the pipe carrying the passwords. Another approach is to use digest authentication, another authentication scheme built into HTTP. Digest authentication prevents eavesdropping by never sending the password across the wire. Instead, the authentication algorithm relies on sending hash values computed from the password and other values known only by the client and server. This makes it possible for the server to recompute the hash found in an incoming message to validate that client has possession of the password. Heres how it works. When a client attempts to access a protected resource, the server returns a 401 (Unauthorized) response to the client along with a WWW-Authenticate header indicating that it requires digest authentication along with some supporting data. Once the client
receives this, it can generate an Authorization header containing the computed hash value and send an identical request back to the server including the new header. Assuming the client generates a valid Authorization header, the server will allow access to the resource. Digest authentication is better than basic but its still subject to offline dictionary and brute force attacks (unless you enforce a really strong password policy), and its not as widely supported by Web browsers and servers. Another approach is to avoid both basic and digest authentication and implement a custom authentication scheme around the Authorization header. Many of these schemes use a custom Hash Message Authentication Code (HMAC) approach, where the server provides the client with a user id and a secret key through some out-of-band technique (e.g., the service sends the client an e-mail containing the user id and secret key). The client will use the supplied secret key to sign all requests. For this approach to work, the service must define an algorithm for the client to follow when signing the requests. For example, it must outline how to canonicalize the message and which parts should be included in the HMAC signature along with the secret key. This is important because the client and service must follow the same algorithm for this to work. Once the client has generated the HMAC hash, it can include it in the Authorization header along with the user id:
Authorization: skonnard:uCMfSzkjue+HSDygYB5aEg==
When the service receives this request, it will read the Authorization header and split out the user id and hash value. It can find the secret for the supplied user id and perform the same HMAC algorithm on the message. If the computed hash matches the one in the message, we know the client has possession of the shared secret and is a valid user. We also know that no one has tampered with whatever parts of the message were used to compute the HMAC hash (and that could be the entire message). In order to mitigate replay attacks, we can include a timestamp in the message and include it in the hash algorithm. Then the service can reject out-of-date messages or recently seen timestamp values. The HMAC approach is superior to both basic and digest authentication, especially if the generated secrets are sufficiently long and random, because it doesnt subject the password to dictionary or brute force attacks. As a result, this technique is quote common in todays public facing RESTful services. For the service were designing, we could pick any of these techniques to authenticate users. Well assume an HMAC approach for our service, and that each user will be assigned a secret key through an out-of-band e-mail after creating a new user account. And for all of the nonpublic resources, well look for a valid HMAC hash in the Authorization header and return a 401 (Unauthorized) when necessary. Now that we have a way for users to prove who they are, well need logic to authorize their requests, in other words, to decide what they are allowed to do. For example, any authenticated or anonymous user may retrieve any public bookmark, while private bookmarks may only be
retrieved by the authenticated user who owns them. Well see how to implementation this authorization logic later in the paper.
However, when a user retrieves his user account resource, the service will supply a different representation containing a little more information, in this case an Id and a link. Well provide the Id that links back to this particular user resource and a link to this users list of public bookmarks:
<User> <Bookmarks>http://contoso.com/bookmarkservice/skonnard</Bookmarks> <Email>[email protected]</Email>
There may be other pieces of information that make sense only in either the request or response representations. A valid user can update this representation with a new e-mail address or a different name and PUT it back to the same URI to perform an update. A users public profile will provide yet another representation because we probably dont want to share one users e-mail address with another. Heres what well use for the user profile resource:
<UserProfile> <Bookmarks>http://contoso.com/bookmarkservice/skonnard</Bookmarks> <Id>http://contoso.com/bookmarkservice/skonnard</Id> <Name>Aaron Skonnard</Name> </UserProfile>
Now lets turn our attention to bookmark resources. For our example, a bookmark is a pretty simple data set. When a user creates a bookmark, it must provide a title, a URL, some optional tags, and a public/private flag. Well support the following representation for creating new bookmarks:
<Bookmark> <Public>true</Public> <Tags>REST,WCF</Tags> <Title>Aarons Blog</Title> <Url>http://pluralsight.com/aaron</Url> </Bookmark>
And well use a slightly enhanced representation when returning bookmark resources that includes an Id, additional information about the user who created it, and a last-modified time:
<Bookmark> <Id>http://contoso.com/bookmarkservice/users/skonnard/bookmarks/13</Id> <LastModified>2008-03-12T00:00:00</LastModified>
A list of bookmarks will simply be represented by a <Bookmarks> element, containing a list of child <Bookmark> elements as shown here:
<Bookmarks> <Bookmark> <Id>http://contoso.com/bookmarkservice/users/skonnard/bookmarks/13</Id> <LastModified>2008-03-12T00:00:00</LastModified> <Public>true</Public> <Tags>REST,WCF</Tags> <Title>Aaron's Blog</Title> <Url>http://pluralsight.com/aaron</Url> <User>skonnard</User> <UserProfile>http://contoso.com/bookmarkservice/users/skonnard/profile </UserProfile> </Bookmark> <Bookmark>...</Bookmark> <Bookmark>...</Bookmark> </Bookmarks>
These representations make is possible to navigate between different types of resources, and they are simple to consume in any programming framework that includes a simple XML API.
This is an example of what the new user account resource would look like in JSON:
{User:{Email:'[email protected]', Name:'Aaron Skonnard'}}
This is just another representation of the same resource. Again, the reason for supporting multiple formats is to make things easier for certain types of clients. It wouldnt be hard to also support form-encoding to simplify things for Web browser forms or other text-based formats (e.g., CSV) in order to accommodate even more client application scenarios (e.g., Microsoft Excel).
One of the benefits of using XHTML as the representation format is that it can be rendered in a Web browser for human viewing during development. With XHTML, you can represent lists of items and you can use forms to encode additional metadata that describes how to interact with other linked resources. AtomPub is another popular choice because it was specifically designed to represent and manipulate collections of resources. There are many feed-aware clients (including modern Web browsers) that know how to render Atom feeds, providing a human view that can prove helpful during development. The main downside to using either of these formats is that they are somewhat constrained in terms of the data set the XML vocabulary was designed to model (e.g., theres not a natural way to map a purchase order into an Atom entry). Both of these formats do provide extensibility elements for injecting custom XML fragments, also commonly referred to as micro-formats. However, introducing micro-formats begins to counteract the benefit of using a standard representation format. For our bookmark service, in addition to the XML format weve defined, well also expose the public bookmarks as an Atom feed. If were going to support Atom feeds, we should probably also support RSS feeds since theyre very similar formats and it might open the door for more feed readers. Hence, well support both by adding feed to the URI along with a format parameter to indicate atom or rss:
feed?tag={tag}&format={format}
Now lets look at how we can represent bookmarks using Atom. Atom defines a standard format for representing feeds, which are essentially just lists of time-stamped entries that can really represent anything. For example, we can represent a list of bookmarks using this type of Atom feed:
<feed xmlns="http://www.w3.org/2005/Atom"> <title>Public Bookmarks</title> <updated>2008-09-13T18:30:02Z</updated> <id>http://contoso.com/bookmarkservice/feed</id> <entry> <author> <name>Aaron Skonnard</name> </author> <title>Aarons Blog</title>
<link href="http://pluralsight.com/aaron"/> <id>http://contoso.com/bookmarkservice/users/skonnard/bookmarks/13</id> <updated>2008-09-13T18:30:02Z</updated> <category term="REST,WCF"/> </entry> <entry>...</entry> <entry>...</entry> </feed>
Weve simply defined a mapping between our bookmark fields and the elements that make up an Atom <entry>. Once you have your data in Atom/RSS format, it can be easily consumed by any Atom/RSS compatible client. Figure 6 shows an Atom bookmark feed rendered in Internet Explorer and notice how were able to search, sort and filter this feed within the browser using the right-hand control pane. Figure 6: An Atom feed rendered in Internet Explorer
AtomPub defines a standard way to represent a service document, which is a high-level description of the collections supported by a service. AtomPub also defines a standard API for manipulating entries using the standard Atom feed format along with GET, POST, PUT, and DELETE requests. The following shows an example AtomPub service document describing our services bookmarks collections:
<service xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom"> <workspace> <atom:title>Contoso Bookmark Service</atom:title> <collection href="http://contoso.com/bookmarkservice/" > <atom:title>Public Bookmarks</atom:title> </collection> <collection href="http://contoso.com/bookmarkservice/skonnard" > <atom:title>Aaron Skonnard's Public Bookmarks</atom:title> </collection> <collection>...</collection> </workspace> </service>
Figuring out the right representation to use for your RESTful service is primarily about figuring out what types of clients you want to accommodate and what scenarios you want to facilitate.
The service can return the comma-separated list of supported HTTP methods to the client in the Allow header. The following example shows how to issue an OPTIONS request for a users bookmark collection:
OPTIONS http://contoso.com/bookmarkservice/skonnard/bookmarks HTTP/1.1
Assuming the client is authenticated as skonnard, the service will return the following response indicating that the resource supports GET and POST requests:
HTTP/1.1 200 OK Allow: GET, POST
However, if someone other than skonnard issues the same OPTIONS request, the service will return the following response indicating that only GET requests are supported:
HTTP/1.1 200 OK Allow: GET
HTTP also comes with a sophisticated built-in content negotiation mechanism. Clients can provide the User-Agent and the various Accept headers to indicate what media types (or representations) are acceptable for the response. The server can then pick a representation best suited for that particular client. When multiple acceptable representations might exist, the server can return a 300 (Multiple Choices) response including the URIs for each supported resource representation. The combination of HEAD, OPTIONS, and the content negotiation headers provides a foundation for runtime discovery. If you want to make it possible for clients to discover the exact representation formats, you can provide clients with schema definitions that can be used to generate the client-side processing logic. Or you can choose to use a standard format like XHTML or Atom that removes the need for this altogether. In addition to all of this, there are a few service description languages that can be used to fully describe RESTful services. WSDL 2.0 is one such language and the Web Application Description Language (WADL) is another, but not many toolkits provide support for either today. Although having WSDL-based code-generation would be a huge win for some consumers, not having it hasnt been a huge show-stopper thus far. After all, there are many large-scale RESTful services around getting by just fine without it. Nevertheless, my hope is that well see additional innovation in this area in the years ahead.
Web today that break this rule. A service designed like this isnt fully RESTful its more of a hybrid REST/RPC service . This type of design misuses HTTPs uniform interface and violates the semantics for GET, which can cause big problems down the road when dealing with retries and caching. Like we learned earlier, GET is intended to be a safe operation (no side effects) but these operations do cause side effects. This can lead to problems since other components will make incorrect assumptions about these resources. The primary reason some services do things this way is because many of todays Web browsers and firewalls only allow GET and POST requests. Due to this limitation, many sites overload GET or POST to fake PUT and DELETE requests. This can be accomplished by specifying the real HTTP method in a custom HTTP header. A common HTTP header used for this purpose is the X-HTTP-Method-Override header, which you can use to overload POST with a DELETE operation as shown in this example:
POST /bookmarkservice/skonnard/bookmarks/123 HTTP/1.1 X-HTTP-Method-Override: DELETE
Using this technique is widely considered an acceptable practice for working around the limitations of todays Web infrastructure because it allows you to keep your URI design free of RPCisms.
representations including XML, JSON, RSS and Atom. In addition to this core support, Microsoft is now shipping the WCF REST Starter Kit, which provides additional APIs, extension methods, and various Visual Studio project templates to simplify REST development. The WCF REST Resource Kit is expected to evolve through CodePlex, and some of its features may make their way into future versions of the .NET framework. The ADO.NET team was able to leverage the WCF REST support when they built ADO.NET Data Services, a higher-level REST framework that almost fully automates the process of exposing RESTful services around underlying data/object entities using AtomPub. ADO.NET Data Services is a great example of whats possible when using WCF as your underlying REST communication framework. Throughout this section, well take a closer look at the built-in REST support found in WCF 3.5, the REST Starter Kit, and ADO.NET Data Services. But first, lets look at how youd have to do it without WCF.
Check out Figure 7 to get a feel for what this code might look like. Ive provided a few methods that abstract away a lot of details like Matches and ExtractVariables but there is still a lot of tedious work going on around the actual service logic (e.g., dealing with user accounts and bookmarks). Figure 7: A sample IHttpHandler implementation
VB
C# C++ F# JScript
public class BookmarkService : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { Uri uri = context.Request.Url; // compare URI to resource templates and find match if (Matches(uri, "{username}?tag={tag}")) { // extract variables from URI Dictionary<string, string> vars = ExtractVariables(uri, "{username}?tag={tag} "); string username = vars["username"]; string tag = vars["tag"]; // figure out which HTTP method is being used switch (context.Request.HttpMethod) { // dispatch to internal methods based on URI and HTTP method // and write the correct response status & entity body case "GET": List<Bookmark> bookmarks = GetBookmarks(username, tag); WriteBookmarksToResponse(context.Response, bookmarks); SetResponseStatus(context.Response, "200", "OK"); break; case "POST": Bookmark newBookmark = ReadBookmarkFromRequest(context.Request); string id = CreateNewBookmark(username, newBookmark); WriteLocationHeader(id); SetResponseStatus(context.Response, "201", "Created"); break; default: SetResponseStatus(context.Response, "405", "Method Not Allowed"); } } if (Matches(uri, "users/{username}/bookmarks/{id}")) { // dispatch to internal methods based on URI and HTTP method // and write the correct response status & entity body ... } ... // match addition URI templates here } }
WCF 3.5 provides a programming model that shields you from the tedious aspects of this code it shields you from most HTTP protocol details, URIs, and the resource representations transmitted on the wire. It accomplishes this by providing a built-in URI template programming model that makes it easy to match URIs and extract variables. It also provides a new set of attributes for mapping HTTP method + URI template combinations to method signatures, and some serialization improvements for supporting different types of resource representations. And, of course, it provides the underlying runtime components that know how to bring these new RESTful programming constructs to life.
For our bookmarking service, the DataContractSerializer should be sufficient for our needs. So well define a few classes that will work with DataContractSerializer to represent our resources (see Figure 8). Figure 8: User Account and Bookmark Resource Classes
VB C# C++ F# JScript
public class User { public Uri Id { get; set; } public string Username { get; set; } public string Name { get; set; } public string Email { get; set; } public Uri Bookmarks { get; set; } } public class UserProfile { public Uri Id { get; set; } public string Name { get; set; } public Uri Bookmarks { get; set; } } public class Bookmark { public Uri Id { get; set; } public string Title { get; set; } public Uri Url { get; set; } public string User { get; set; } public Uri UserLink { get; set; } public string Tags { get; set; } public bool Public { get; set; } public DateTime LastModified { get; set; } } [CollectionDataContract] public class Bookmarks : List<Bookmark> { public Bookmarks() { } public Bookmarks(List<Bookmark> bookmarks) : base(bookmarks) {}
As of .NET Framework 3.5 SP1, DataContractSerializer now supports serializing plain-old CLR objects (POCO, for short) without any serializer attributes as shown in the example above. Before SP1, we would have had to annotate the User and Bookmark classes with [DataContract] and [DataMember]; now you dont have to. If you want more control over naming, default values, and ordering, you can always add these attributes back to the class definition but for this example, well just accept the default mapping. In this case I still had to annotate the collection class with [CollectionDataContract] in order to make the name of the root element <Bookmarks> instead of the default <ArrayOfBookmark>. DataContractSerializer treats all of the fields found on User and Bookmark as optional by default, so these classes can handle the input/output representations for each resource. Weve also defined a couple of custom collection types for modeling lists of users and bookmarks. These classes all conform to the resource representations we defined earlier in the previous section.
VB C# C++ F# JScript
public class BookmarkService { Bookmarks GetPublicBookmarks(string tag) {...} Bookmarks GetUserPublicBookmarks(string username, string tag) {...} Bookmarks GetUserBookmarks(string username) {...} UserProfile GetUserProfile(string username) {...}
User GetUser(string username) {...} void PutUser(string username, User user) {...} void DeleteUser(string username) {...} Bookmark GetBookmark(string username, string id) {...} void PostBookmark(string username, Bookmark newValue) {...} void PutBookmark(string username, string id, Bookmark bm) {...} void DeleteBookmark(string username, string id) {...} }
Youll notice that most of these methods operate on User and Bookmark objects or their respective collection classes. Some of them also require extra parameters like username, id, and tag, which well harvest from the incoming URI according to the URI template variables.
VB C# C++ F# JScript
Uri baseUri = new Uri("http://contoso.com/bookmarkservice"); UriTemplate uriTemplate = new UriTemplate( "users/{username}/bookmarks/{id}"); // generate a new bookmark URI Uri newBookmarkUri = uriTemplate.BindByPosition(baseUri, "skonnard", "123"); // match an existing bookmark URI UriTemplateMatch match = uriTemplate.Match(baseUri, newBookmarkUri); System.Diagnostics.Debug.Assert(match != null); Console.WriteLine(match.BoundVariables["username"]); Console.WriteLine(match.BoundVariables["id"]);
The UriTemplateTable class provides a mechanism for managing a collection of UriTemplate objects. This makes it easy to call Match on the table to find all templates that match the supplied Uri. Alternatively, you can call MatchSingle to ensure it matches only a single UriTemplate in the table. The WCF Web programming model makes it easy to map UriTemplate objects to your method signatures through the new [WebGet] and [WebInvoke] attributes. Once you have these attributes enabled, WCF will perform its internal method dispatching based on UriTemplate matching logic.
VB C# C++ F# JScript
[ServiceContract] public partial class BookmarkService { [WebGet(UriTemplate = "?tag={tag}")] [OperationContract] Bookmarks GetPublicBookmarks(string tag) {...} [WebGet(UriTemplate = "{username}?tag={tag}")] [OperationContract] Bookmarks GetUserPublicBookmarks(string username, string tag) {...} [WebGet(UriTemplate = "users/{username}/bookmarks?tag={tag}")] [OperationContract] Bookmarks GetUserBookmarks(string username, string tag) {...} [WebGet(UriTemplate = "users/{username}/profile")] [OperationContract] UserProfile GetUserProfile(string username) {...} [WebGet(UriTemplate = "users/{username}")] [OperationContract] User GetUser(string username) {...} [WebGet(UriTemplate = "users/{username}/bookmarks/{bookmark_id}")] [OperationContract] Bookmark GetBookmark(string username, string bookmark_id) {...} ... }
Well handle the remaining HTTP methods with the [WebInvoke] attribute. It works a lot like [WebGet], but with a couple of key differences. Since it can be used with any HTTP method, you must specify which HTTP method it will handle via the Method property. And for PUT and POST methods, where the client will be supplying an entity body, youll need to add one more parameter to the method signature capable of holding the deserialized entity body. It should come after all of the UriTemplate parameters. Figure 11 shows how to complete our HTTP mapping for the bookmark service using [WebInvoke]. Figure 11: Applying [WebInvoke] to BookmarkService
VB C# C++ F# JScript
[ServiceContract] public partial class BookmarkService { [WebInvoke(Method = "PUT", UriTemplate = "users/{username}")] [OperationContract] void PutUserAccount(string username, User user) {...} [WebInvoke(Method = "DELETE", UriTemplate = "users/{username}")] [OperationContract] void DeleteUserAccount(string username) {...} [WebInvoke(Method = "POST", UriTemplate = "users/{username}/bookmarks")] [OperationContract] void PostBookmark(string username, Bookmark newValue) {...} [WebInvoke(Method = "PUT", UriTemplate = "users/{username}/bookmarks/{id")] [OperationContract] void PutBookmark(string username, string id, Bookmark bm) {...} [WebInvoke(Method = "DELETE", UriTemplate = "users/{username}/bookmarks/{id}")] [OperationContract] void DeleteBookmark(string username, string id) {...} ... }
Notice how each of these methods takes either a User or Bookmark object as the final parameter in the method signature WCF will deserialize the request body and pass it to us through this parameter.
However, there are still some aspects of the HTTP programming model that we do need to manage from within your method implementations. For example, in most of our methods, well need to inject response headers, set the response status code and description, and generate outbound links. So how do we get access to the underlying HTTP methods within our WCF method implementations? This is where the WebOperationContext class comes into play. WebOperationContext provides properties for accessing the IncomingRequest and OutgoingResponse messages, which you can use to inspect the HTTP request or to manipulate the HTTP response before its sent. For example, you can simply call WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound() to return a 404 (Not Found) response to the client. WebOperationContext is your primary interface to HTTP. You simply need to implement the logical HTTP operations for each of the resources exposed by your service. To help you get a feel for the type of code youll be writing within each method body, Ive provided a few complete method implementations for you to inspect in Figure 12. Notice how they set different HTTP response codes, headers, and create outbound links through helper methods. The GetUserLink help generates an outbound link based on the same UriTemplates used by the service. Figure 12: Sample method implementations for user account resources
VB C# C++ F# JScript
[ServiceContract] public partial class BookmarkService { // in-memory resource collections Dictionary<string, User> users = new Dictionary<string, User>(); Dictionary<string, Bookmark> bookmarks = new Dictionary<string, Bookmark>(); [WebGet(UriTemplate = "users/{username}")] [OperationContract] User GetUserAccount(string username) { if (!IsUserAuthorized(username))
{ WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; return; } User user = FindUser(username); if (user == null) { WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound(); return null; } return user; } [WebInvoke(Method = "PUT", UriTemplate = "users/{username}")] [OperationContract] void PutUserAccount(string username, User newValue) { User user = FindUser(username); if (user == null) { // set status to created and include new URI in Location header WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated( GetUserLink(username)); ... // process new user backend logic } else if (!IsUserAuthorized(username)) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; return; } // create or update new user, but don't let user set Id/Bookmarks newValue.Id = GetUserLink(username); newValue.Bookmarks = GetUserBookmarksLink(username); users[username] = newValue; } ... // remaining methods ommitted }
custom dispatching logic based on the [WebGet] and [WebInvoke] attributes and their corresponding UriTemplates. Figure 13 illustrates how to accomplish this in your application configuration file. Figure 13: Configuring WCF "Web" Services
VB C# C++ F# JScript
<configuration> <system.serviceModel> <services> <service name="BookmarkService"> <endpoint binding="webHttpBinding" contract="BookmarkService" behaviorConfiguration="webHttp"/> </service> </services> <behaviors> <endpointBehaviors> <behavior name="webHttp"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> <configuration>
With this configuration in place, you can simply create a ServiceHost instance based on BookmarkService and open it to get your RESTful service up and running:
ServiceHost host = new ServiceHost(typeof(BookmarkService), new Uri("http://localhost:8080/bookmarkservice")); host.Open();
... // keep the host open until you want to shut it down
In this example, we specified the base URI for the service when constructing the ServiceHost, and that same address will be used for the endpoint, since we didnt specify an address on the endpoint itself. If the hosting experience I just described feels a little tedious to you, worry not, WCF has made things even easier through a custom ServiceHost-derived class called WebServiceHost. When you use WebServiceHost instead of ServiceHost, it will automatically create a Web endpoint for you using the base HTTP address and configure the injected endpoint with the WebHttpBehavior. So this example is equivalent to the prior example, only this time we dont need a configuration file at all:
WebServiceHost host = new WebServiceHost(typeof(BookmarkService), new Uri("http://localhost:8080/bookmarkservice")); host.Open(); ... // keep the host open until you want to shut it down
This little gem also greatly simplifies the process of hosting WCF Web services within IIS/ASP.NET through .svc files. By specifying the mapping from the .svc file to the service class name, we can take advantage of the Factory attribute to specify the WebServiceHostFactory as shown here:
<%@ ServiceHost Service="BookmarkService" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>
This custom ServiceHostFactory intercepts the ServiceHost creation process at run time and generates WebServiceHost instances instead. In this case, the base URI of the service will simply be the URI of the .svc file and no further configuration is necessary, unless you need to configure additional behaviors. If youre hosting your WCF Web services in IIS/ASP.NET, its also a good idea to enable the ASP.NET compatibility mode within the WCF runtime. Doing so makes it possible for you to access the HttpContext object managed by ASP.NET from within your WCF methods. You enable ASP.NET compatibility by adding the following global flag to your Web.config file:
<configuration> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel>
</configuration>
Then, youll also want to declare on your service class whether you allow, require, or dont allow ASP.NET compatibility mode as illustrated here:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceContract] public partial class BookmarkService { ...
You will most likely end up hosting your WCF Web services in IIS/ASP.NET using .svc files like Ive just shown you. One issue with using this technique is what the final URIs will look like. If the .svc file is located at http://localhost/bookmarkservice.svc, the final service URIs end up like this:
http://localhost/bookmarkservice.svc/skonnard?tag=wcf http://localhost/bookmarkservice.svc/users/skonnard/bookmarks/13 ...
The .svc portion of the URI is really a .NET implementation detail and not something that you probably want to have in the URI. The easiest way to work around this issue today is to leverage the Microsoft URL Rewrite Module for IIS 7.0, which makes it possible to remove the .svc from the path segment. For a complete example on how to do this, see Rob Bagbys blog post on Controlling the URI. Once youve applied the URL Rewrite Module to remove .svc, your URIs will look like this:
http://localhost/bookmarkservice/skonnard?tag=wcf http://localhost/bookmarkservice/users/skonnard/bookmarks/13 ...
Once you have your WCF service implemented, configured, and hosted, you can begin testing your RESTful service by simply browsing to it (see Figure 14). You can also use any HTTP client utility to test the non-GET operations for creating, updating, and deleting resources at this point. Figure 14: Browsing to your WCF RESTful service
Weve also added the RequestFormat/ResponseFormat properties, specifying WebMessageFormat.Json, where applicable. Figure 15: Defining a JSON-specific interface
VB C# C++ F# JScript
[ServiceContract] public partial class BookmarkService { ... [WebInvoke(Method = "POST", RequestFormat=WebMessageFormat.Json, UriTemplate = "users/{username}/bookmarks?format=json")] [OperationContract] void PostBookmarkAsJson(string username, Bookmark newValue) { HandlePostBookmark(username, newValue); } [WebGet(ResponseFormat= WebMessageFormat.Json, UriTemplate = "users/{username}/bookmarks/{id}?format=json")] [OperationContract] Bookmark GetBookmarkAsJson(string username, string id) { HandleGetBookmark(username, id); } ... }
Notice how these methods are also dispatching to internal methods called HandlePostBookmark and HandleGetBookmark, which are format independent. Both the XML and JSON methods can call these same internal methods to perform the business logic, reducing code duplication. If you navigate to one of the JSON URIs in a browser, youll be prompted to save the file to disk. Go ahead and save the file as a .txt file and you can inspect the JSON response. With JSON enabled, Ajax clients can more easily communicate with our RESTful service and consume the data we send back.
WCF even goes one step further on the Ajax front by providing a special behavior that can automatically expose a WCF service as an Ajax-friendly JSON service. This is made possible by EnableWebServiceBehavior, which is wired-up when you use the new WebScriptServiceHost to host your services. This behavior not only exposes your WCF service, it also adds behavior to automatically generate Javascript proxies for Web browsers upon request. If you browse to your services base address and add /js to the end, youll get the auto-generated Javascript proxy. This makes it really simple for Javascript code running in a browser to call your service. This technique is only useful for simple Ajax-based services that are primarily serving up data to Web pages. You cannot use UriTemplates in conjunction with this type of Ajax-based service because the auto-generated JavaScript proxies arent capable of dealing with them properly today.
VB C# C++ F# JScript
[WebGet(UriTemplate ="feed?tag={tag}&format=atom")]
[ServiceKnownType(typeof(Rss20FeedFormatter))] [ServiceKnownType(typeof(Atom10FeedFormatter))] [OperationContract] SyndicationFeedFormatter GetPublicBookmarksFeed(string tag, string format) { Bookmarks publicBookmarks = HandleGetPublicBookmarks(tag); WebOperationContext ctx = WebOperationContext.Current; List<SyndicationItem> items = new List<SyndicationItem>(); foreach (Bookmark bm in publicBookmarks) { SyndicationItem item = new SyndicationItem(bm.Title, "", bm.Url, bm.Id.ToString(), new DateTimeOffset(bm.LastModified)); foreach (string c in bm.Tags.Split(',')) item.Categories.Add(new SyndicationCategory(c)); item.Authors.Add(new SyndicationPerson("", bm.User, "")); items.Add(item); } SyndicationFeed feed = new SyndicationFeed() { Title = new TextSyndicationContent("Public Bookmarks"), Id = ctx.IncomingRequest.UriTemplateMatch.RequestUri.ToString(), LastUpdatedTime = DateTime.Now, Items = items }; if (format.Equals("atom")) return new Atom10FeedFormatter(feed); else return new Rss20FeedFormatter(feed); }
Notice how in Figure 16 the method is defined to return a SyndicationFeedFormatter type but the implementation actually returns an instance of either Rss20FeedFormatter or Atom10FeedFormater. To make this work, we had to annotate the method with two [ServiceKnownType] attributes, one specifying each of the derived SyndicationFeedFormatter types we needed to return. This type of feed can be consumed and viewed by any RSS/Atom reader, which includes most of todays modern Web browsers (see Figure 6), and it can be easily syndicated by other feed-savvy sites. There is a great deal of RSS/Atom infrastructure available on the Web today, so exposing your data this way opens up numerous possibilities around how the data can be harvested. WCF also provides built-in classes for AtomPub, a standard API for interacting with Atom-based collections using a RESTful interface. You can think of AtomPub as a standard application of the HTTP uniform interface but applied specifically to Atom feeds, which are modeled as collections of entries. The WCF AtomPub support is found across several classes including ServiceDocument, ServiceDocumentFormatter, AtomPub10ServiceDocumentFormatter, and Workspace all found in the System.ServiceModel.Syndication namespace. Figure 17 illustrates how to use these classes to generate an AtomPub service document describing the feeds provided by our service.
VB C# C++ F# JScript
ServiceDocument HandleGetServiceDocument() { List<ResourceCollectionInfo> collections = new List<ResourceCollectionInfo>(); collections.Add(new ResourceCollectionInfo( new TextSyndicationContent("Public Bookmarks"), GetPublicBookmarksFeedLink())); foreach (string user in users.Keys) collections.Add( new ResourceCollectionInfo( new TextSyndicationContent( string.Format("Public Bookmarks by {0}", user)), GetUserBookmarksFeedLink(user))); List<Workspace> workspaces = new List<Workspace>(); workspaces.Add(new Workspace( new TextSyndicationContent("Contoso Bookmark Service"), collections)); return new ServiceDocument(workspaces); }
To fully support the AtomPub protocol, wed need to redesign our service quite a bit to do everything in terms of Atom feeds and entries. In other words, wed no longer use our current representations for user accounts and bookmarks. Instead, wed figure out a way to represent user accounts and bookmarks within the AtomPub format and implement the appropriate HTTP methods (according to the AtomPub specification) using the [WebGet] and [WebInvoke] attributes.
18 shows how to implement HMAC authentication by simply signing the URL with the secret key. Figure 18: Implementing HMAC authentication
VB C# C++ F# JScript
private bool AuthenticateUser(string user) { WebOperationContext ctx = WebOperationContext.Current; string requestUri = ctx.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); string authHeader = ctx.IncomingRequest.Headers[HttpRequestHeader.Authorization]; // if supplied hash is valid, user is authenticated if (IsValidUserKey(authHeader, requestUri)) return true; return false; } public bool IsValidUserKey(string key, string uri) { string[] authParts = key.Split(':'); if (authParts.Length == 2) { string userid = authParts[0]; string hash = authParts[1]; if (ValidateHash(userid, uri, hash)) return true; } return false; } bool ValidateHash(string userid, string uri, string hash) { if (!UserKeys.ContainsKey(userid)) return false; string userkey = UserKeys[userid]; byte[] secretBytes = ASCIIEncoding.ASCII.GetBytes(userkey); HMACMD5 hmac = new HMACMD5(secretBytes); byte[] dataBytes = ASCIIEncoding.ASCII.GetBytes(uri); byte[] computedHash = hmac.ComputeHash(dataBytes);
You can simply call this method from each [WebGet] and [WebInvoke] operation that requires authentication as illustrated here:
if (!AuthenticateUser(username)) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; return; }
Once weve authenticated a user, we can save the users identity somewhere (e.g., as a user principal). In this example, Im storing in the message properties so that well be able to authorize the user within operations that need to further control access to certain resources. You could make this implementation more elegant by integrating with [PrincipalPermission] or by providing your own security attributes. We could have also implemented this logic as a custom WCF channel, thereby removing the need to make calls to AuthenticateUser altogether and simplifying reuse, but building a custom channel is not an easy proposition. The WCF REST Starter Kit simplifies this by introducing a new request interception model specifically for situations like this when using the WebHttpBinding.
Microsoft.ServiceModel.Web Extensions
Once you start building RESTful services, youll begin running into some common pain points that feel tedious or cumbersome, even when using a modern framework like WCF (for example, writing the various HTTP status codes and descriptions to the response message). Hence, the WCF REST Starter Kit provides a new suite of APIs designed to address some of those common pain points in an effort to make building RESTful services even easier with WCF moving forward. These new classes and extension methods are found in the new Microsoft.ServiceModel.Web assembly and namespace. As an example, the WCF REST Starter Kit introduces a new WebProtocolException class that you can throw in your service logic to specify an HTTP status code, which feels much more natural to a typical .NET developer. In addition to this, the WCF REST Starter Kit also comes with a new WebServiceHost2 class and the corresponding WebServiceHost2Factory class, which provides a zero-config experience tailored for a RESTful service. This custom service host introduces some new extensions and behaviors including support for an automatic help page that describes your RESTful service. This new help page is a huge step forward for RESTful service development. By default, you navigate to it at /help. And you can annotate your Web operations with [WebHelp] to provide human-readable descriptions for each operation found on your service. This help pages makes it easy for consumers to figure out the services URI design, retrieve resource schemas, and view examples of them. The obvious next step is to provide a REST-savvy client experience on top of this complete with code generation. The WCF REST Starter Kit also provides a simpler model for controlling caching through the [WebCache] attribute that you can declaratively apply to your service operations. And it adds numerous extension methods to the WebOperationContext class that address some common REST-oriented tasks. And finally, the WCF REST Starter Kit introduces a new request interception model (based on RequestInterceptor) that you can use for different types of HTTP interception tasks such as authentication. This model makes it much easier to introduce your own request interception logic without having to deal with writing a custom WCF message inspector and an associated behavior. (see Figure 19) Figure 19: Automatic help page for RESTFul services
The HTTP Plain XML Service is different in that the generated service doesnt support the full HTTP interface. Instead, it provides simple GET and POST operations for those who dont care about fully conforming to the RESTful design principles weve discussed and would rather build a REST/RPC hybrid service by overloading GET and POST. I personally wouldnt recommend this approach. The last few Atom-related project templates add value when working with feeds. The Atom Feed Service template provides a sample implementation that shows how to programmatically generate and return a SyndicationFeed instance. You simply need to change the implementation to fill in your business data as appropriate. And finally, the Atom Publishing Protocol Service template provides a complete skeleton implementation for a fully compliant AtomPub service, greatly reducing the amount of code you have to write for this scenario, and allowing you to focus primarily on how to map your resources to Atom. Figure 21 for a description of each project template. When you use one of these project templates, your remaining tasks include modifying the resource class definitions, propagating those changes throughout the implementation (you can use Visual Studio refactoring here), refining the URI design when needed, and implementing the method stubs for each HTTP operation. Figure 20: The WCF REST Starter Kit project templates
The REST Singleton Service produces a service that exposes the full HTTP interface (GET, POST, PUT, and DELETE) around a singleton resource, and it automatically provides both XML and JSON representations for the underlying resource. The REST Collection Service does the same thing only it exposes a collection of underlying resources, as opposed to a singleton resource. This is probably where you want to start. The HTTP Plain XML Service is different in that the generated service doesnt support the full HTTP interface. Instead, it provides simple GET and POST operations for those who dont care about fully conforming to the RESTful design principles weve discussed and would rather build a REST/RPC hybrid service by overloading GET and POST. I personally wouldnt recommend this approach. The last few Atom-related project templates add value when working with feeds. The Atom Feed Service template provides a sample implementation that shows how to programmatically generate and return a SyndicationFeed instance. You simply need to change the implementation to fill in your business data as appropriate. And finally, the Atom Publishing Protocol Service template provides a complete skeleton implementation for a fully compliant AtomPub service, greatly reducing the amount of code you have to write for this scenario, and allowing you to focus primarily on how to map your resources to Atom. Figure 21: WCF REST Starter Kit project template descriptions
Project Template
Description
HTTP Plain XML Produces a service with simple GET and POST methods that you can build on for Service plain-old XML (POX) services that dont fully conform to RESTful design principles, but instead rely only on GET and POST operations. REST Singleton Service Produces a service that defines a sample singleton resource (SampleItem) and the full HTTP interface for interacting with the singleton (GET, POST, PUT, and DELETE) with support for both XML and JSON representations. Similar to the REST Singleton Service only it also provides support for managing a collection of SampleItem resources. Produces a service that produces a sample Atom feed with dummy data.
REST Collection Service Atom Feed Service Atom Publishing Protocol Service
Produces a full-fledged AtomPub service capable of managing collections of resources as well as media entries.
Lets walk through a few examples using the WCF REST Starter Kit to help illustrate how it can simplify the process of building these types of RESTful services.
Lets start by creating a bookmark collection service similar to what we built manually earlier in this whitepaper. First, well create a new project by selecting the REST Collection Service template. Then, wed end up with a WCF project containing a resource class named SampleItem along with a service class that implements a RESTful HTTP interface. From this point, we need to make only a few changes. The first thing we need to change is the name of the resource class well change it from SampleItem to Bookmark and Ill take advantage of Visual Studio refactoring to propagate the change throughout the project. Now I can fill in the Bookmark class with the fields I need for representing a bookmark resource. Ill make this Bookmark class look like the one weve been using thus far:
public class Bookmark { public Uri Url { get; set; } public string User { get; set; } public string Title { get; set; } public string Tags { get; set; } public bool Public { get; set; } public DateTime LastModified { get; set; } }
The template also provides a class called SampleItemInfo, which contains an individual Bookmark and the URL that links to it directly. Ill change the name to BookmarkItemInfo and use refactoring to propagate the change. Im also going to change the name of the Item field to Bookmark. Heres what the BookmarkItemInfo class looks like for this example:
public class BookmarkItemInfo { public Bookmark Bookmark { get; set; } public Uri Link { get; set; } }
With these changes in place, my new bookmark collection service is ready to test. Simply press F5 in Visual Studio and it will load the service into the ASP.NET Development Server, and once it does, you should be able to access the service. When the browser first comes up to test the
service, youll see an empty <ArrayOfBookmarkItemInfo> element because the collection is currently empty. At this point you can either use an HTTP client utility to add some bookmarks to the collection (via POST) or you can pre-populate the Bookmark items collection in the service constructor. Once youve populated the Bookmark collection, youll get some <BookmarkItemInfo> elements back when you browse to the services root address (e.g., http://localhost:59256/Service.svc), which essentially requests the entire collection of bookmark resources. See Figure 22 for some sample results. You can then browse to an individual bookmark resource by following one of the <Link> elements returned in the <BookmarkItemInfo> element. For example, you can retrieve the Bookmark with an Id of 3 by browsing to http://localhost:59256/Service.svc/3 in this particular example (see Figure 23). At this point you can also use POST, PUT, and DELETE operations without any additional coding the generated project template already contains a default implementation for each one. You can POST new <Bookmark> elements to the services root address and it will generate a new Bookmark resource and assign it a new Id, and return a 201 Created response with the corresponding Location header. You can also PUT <Bookmark> elements to individual bookmark URIs to perform updates. And you can send DELETE requests to individual bookmark resources to remove them from the collection. As you can see, for this particular type of RESTful service (a collection-oriented service), the WCF REST Starter Kit made it possible to get our implementation up and running with very little coding on our part. And it provides mostly the same functionality that I built myself in our BookmarkService example. It wouldnt be hard to build on this starting point to add user accounts and the remaining functionality. Figure 22: Browsing to the Bookmark collection service
VB C# C++ F# JScript
[ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)] [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceContract] public partial class FeedService { [WebGet(UriTemplate = "?numItems={i}")] [OperationContract] public Atom10FeedFormatter GetFeed(int i) { SyndicationFeed feed; // TODO: Change the sample content feed creation logic here if (i == 0) i = 1; // Create the list of syndication items. These correspond to Atom entries List<SyndicationItem> items = new List<SyndicationItem>(); for (int j = 1; j <= i; ++j) { items.Add(new SyndicationItem() { // Every entry must have a stable unique URI id Id = String.Format( CultureInfo.InvariantCulture, "http://tmpuri.org/Id{0}", j), Title = new TextSyndicationContent( String.Format("Sample item '{0}'", j)), // Every entry should include the last time it was updated LastUpdatedTime = new DateTime( 2008, 7, 1, 0, 0, 0, DateTimeKind.Utc), // The Atom spec requires an author for every entry. Authors = { new SyndicationPerson() { Name = "Sample Author" } },
// The content of an Atom entry can be text, xml, a link or // arbitrary content. In this sample text content is used. Content = new TextSyndicationContent("Sample content"), }); } // create the feed containing the syndication items. feed = new SyndicationFeed() { // The feed must have a unique stable URI id Id = "http://tmpuri.org/FeedId", Title = new TextSyndicationContent("Sample feed"), Items = items, Links = { // A feed should have a link to the service that produced the feed. GetSelfLink(), } }; WebOperationContext.Current.OutgoingResponse.ContentType = AtomContentType; return feed.GetAtom10Formatter(); } ... }
Figure 26: Browsing to the sample collection exposed by the AtomPub service
When you build AtomPub services using the WCF REST Starter Kit, your job is to focus on the logical collections you want to expose. Youll need to define a mapping between your business entity collections and AtomPub collections exposed by the service, which essentially boils down to defining a mapping between your custom business entity classes and the WCF SyndicationFeed/Item classes.
Interestingly, ADO.NET Data Services builds on the WCF REST infrastructure we just discussed. With ADO.NET Data Services, you define the entities you want to expose and the infrastructure takes care of everything else. Lets walk through a few examples.
Doing this adds a new WCF BookmarksEDM.svc endpoint to your site and a code-behind file containing a single class deriving from DataService<T>, which looks like this:
public class BookmarksEDM : DataService< /* TODO: your data source class name */ > {
// This method is called only once to initialize service-wide policies. public static void InitializeService(IDataServiceConfiguration config) { // TODO: set rules to indicate which entity sets are visible, updatable, etc. // Examples: // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead); // config.SetServiceOperationAccessRule("MyServiceOperation", // } } ServiceOperationRights.All);
Since we already have a data source class (the one I generated using the EDM wizard), we can simply modify this to use my BookmarksEntities class. Well also need to uncomment the call to SetEntitySetAccessRule to allow access to the Bookmarks entity. Heres what the final class looks like:
public class BookmarksEDM : DataService<BookmarksModel.BookmarksEntities> { public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("Bookmarks", EntitySetRights.All); } }
We now have a fully functional RESTful service built around the Bookmarks entity model. If you navigate to the BookmarksEDM.svc file at this point, you should get an AtomPub service document back that looks like the one show in Figure 28, listing the collections exposed by the service. Figure 28: The AtomPub service document returned by ADO.NET Data Services
Now, if you browse to the Bookmarks collection by simply adding Bookmarks to the end of the URL, you should get an Atom feed containing the list of Bookmarks found in the database (see Figure 29). Notice that the Bookmark class properties have been serialized within the Atom <content> element. You can further filter your GET queries using the standard URI syntax defined by ADO.NET Data Services, which includes a variety of operators and functions for performing logical data comparisons. For example, the following URL retrieves the bookmarks only for the User named skonnard":
http://localhost:55555/BookmarksEDM.svc/Bookmarks?$filter=User%20eq%20'skonna rd'
The service is also capable of handling POST, PUT, and DELETE requests according to the AtomPub protocol. We now have a fully functional AtomPub service and we hardly wrote any code. The ADO.NET Data Services Framework was able to hide nearly all of the WCF/REST implementation details. Figure 29: The Atom feed returned for the Bookmarks collection
VB C# C++ F# JScript
[DataServiceKey("Id")] public class Bookmark { public string Id { get; set; } public string Url { get; set; } public string User { get; set; } public string Title { get; set; } public string Tags { get; set; } public bool Public { get; set; } public DateTime LastModified { get; set; } } // this class replaces the EDM definition - it provides an in-memory data source public class BookmarkService { static List<Bookmark> bookmarks = new List<Bookmark>(); static BookmarkService() { ... // initialize 'bookmarks' collection with a bunch of objects } public IQueryable<Bookmark> Bookmarks { get { return bookmarks.AsQueryable<Bookmark>(); } } } public class BookmarkDataService : DataService<BookmarkService> { public static void InitializeService(IDataServiceConfiguration config) { config.SetEntitySetAccessRule("Bookmarks", EntitySetRights.All); } }
At this point you end up with an AtomPub service capable responding to GET requests for your in-memory resources. If you want the service to support POST, PUT, and DELETE requests, you must also implement IUpdateable (which was handled for us when using the EDM approach). ADO.NET Data Services is a great example of an automated REST framework built on the WCF REST framework. For more information, see the ADO.NET Data Services learning center on MSDN.
general, the process for programmatically consuming RESTful services is a bit different than the process for consuming SOAP services, because RESTful services typically dont come with a WSDL definition. However, since all RESTful services implement the same uniform interface, consumers inherently know the basic mechanics for interacting with the service through a traditional HTTP library. On the Microsoft platform, you can use MSXML2.XMLHTTP, System.Net, or WCF. Lets look at a few client-side examples.
VB C# C++ F# JScript
Consuming RESTful Services with System.Net If youre writing .NET code, you can take advantage of the System.Net classes to programmatically issue HTTP requests and process the responses. The following code illustrates how easy this can be by using the HttpWebRequest and HttpWebResponse classes:
static void GetPublicBookmarks() { string uri = "http://localhost:55555/bookmarkservice.svc/";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; HttpWebResponse resp = req.GetResponse() as HttpWebResponse; Bookmarks bookmarks = DeserializeBookmarks(resp.GetResponseStream()); foreach (Bookmark bm in bookmarks) Console.WriteLine("{0}\r\n{1}\r\n", bm.Title, bm.Url); }
Its not hard to imagine how you could build a REST client library around your s ervices (that uses code like this) to make them even easier for .NET clients to consume them. Its also not hard to imagine how you could write a generic REST client on top of these classes that can be used with all your services.
Then you can create a WCF channel based on this interface definition using the new WebChannelFactory class that ships with WCF 3.5. This factory knows how to create channels that are aware of the [WebGet] & [WebInvoke] annotations and know how to map the method calls to the uniform HTTP interface. Heres an example of how you can retrieve the public bookmarks tagged with wcf:
VB C# C++ F# JScript
WebChannelFactory<IBookmarkService> cf = new WebChannelFactory<IBookmarkService>( new Uri("http://localhost:55555/BookmarkService.svc")); IBookmarkService channel = cf.CreateChannel(); Bookmarks bms = channel.GetPublicBookmarks("WCF"); foreach (Bookmark bm in bms) Console.WriteLine("{0}\r\n{1}", bm.Title, bm.Url);
If you happened to define your server-side service contract using an interface definition, you can simply share that same interface definition with your WCF client applications. But unfortunately, theres no way to automatically generate the client side RESTful contract from a service description.
VB
C# C++ F# JScript
BookmarkService bookmarkService = new BookmarkService( new Uri("http://localhost:55555/Bookmarks.svc/")); // this generates the following URL: // http://localhost:55555/Bookmarks.svc/Bookmarks()?$filter=substringof('WCF',Tags)& // $orderby=LastModified var bookmarks = from b in bookmarkService.Bookmarks where b.Tags.Contains("WCF") orderby b.LastModified select b; foreach (Bookmark bm in bookmarks) Console.WriteLine("{0}\r\n{1}", bm.Title, bm.Url);
This illustrates the potential of code generation combined with a truly RESTful design. The client is interacting with a resource-centric model, yet all of the HTTP details have been abstracted away. Figure 32: Browsing to ADO.NET Data Service metadata
different programming languages, while hiding the nasty details of the various WS-* protocols being used on the wire. This fact alone is why many major corporations have standardized on SOAP for their services. This is another area where SOAP and REST differ most REST services dont come with this type of code-generation support. Although WSDL makes SOAP easy from an integration perspective, it doesnt necessarily simplify the overall system design. In fact, despite SOAPs attempt to move away from RPC, most SOAP frameworks still push developers towards an RPC model. This can become problematic because its widely believed that RPC doesnt work as well at larger scales, where a more loosely-coupled document-oriented usually works better. At that point, many will realize that most SOAP services are no different than COM+ components, at least from a versioning perspective. REST, on the other hand, encourages a document-oriented model through a uniform interface (although noun versioning remains an issue). Once you understand these realities, it raises some tough questions around which of these models REST or SOAP makes the most sense for a particular system. Anyone who tells you that one of them is always the right choice (regardless of which one), is probably trying to sell something or push an agenda. The reality is: both models provide design philosophies and tools for solving problems, each with their pros and cons. Its your job as an architect/developer to analyze the differences and make a choice.
So what does WS-Security (and the related specifications) enable over the built-in SSL features? It provides a few key features: 1) a single security framework capable of dealing with multiple intermediaries and potentially multiple transports, and 2) support for federated security. The idea of multiple intermediaries is interesting in theory, but doesnt seem to be a common requirement out in the real world. However, support for federated security is becoming more common in large distributed systems so its a requirement that often pushes people towards SOAP and WS-* today. Although you can implement federated security without SOAP and WS-*, there isnt much .NET support for the alternate protocols. There are a variety of specifications that defined HTTPcentric federated security solutions including the SAML 2.0 HTTP bindings, OpenID, and OAuth to name a few. However, since WCF doesnt provide built-in support for any of these specifications today, you either have to find a third-party library or go after it yourself, which isnt a trivial proposition. This is one area where todays REST frameworks need to play catchup. Its likely that the WCF REST Starter Kit will provide additional features and guidance in this area in a future release.
Conclusion
Designing Web services that embrace RESTful principles allows your systems to enjoy the benefits inherent in the Web platform immediately. RESTful design moves you away from traditional RPC and instead requires you to focus on resources, how your resources are identified, and how you interact with your resources through a uniform interface. In my
experience, making this mental shift is the most challenging aspect of moving towards the REST architectural style; the remaining details are easy. Microsoft is strongly committed to REST moving forward. As youve seen, WCF 3.5 makes it easy to support either REST or SOAP, so you can pick what best suits your problem space. The new Web programming model introduced in 3.5 by [WebGet], [WebInvoke], UriTemplate, and SyndicationFeed lowers the bar for authoring RESTful services. And with the introduction of the new WCF REST Starter Kit, theyve lowered the bar even further. The project templates make it possible to get RESTful services up and running in minutes. And for exposing data in your database in traditional CRUD scenarios, it couldnt be easier with ADO.NET Data Services, which practically automate the process of building RESTful data-oriented services.