August 20, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Creating RESTful Web Services with Windows Communication Foundation

  • August 21, 2007
  • By Aaron Lerch
  • Send Email »
  • More Articles »

The OutgoingResponse property exposes an OutgoingWebResponseContext object that encapsulates the response StatusCode, StatusDescription, ContentType, ContentLength, and any other HTTP header value. It includes helper methods for setting the StatusCode to typical values: SetStatusAsCreated and SetStatusAsNotFound. For example, an OperationContract implementation that creates a new blog post should set the response StatusCode to 201 (Created) along with the URI of the created resource:

public void CreatePost(Post post)
{
   WebOperationContext.Current;

   if (post == null)
   {
      context.OutgoingResponse.StatusCode =
         System.Net.HttpStatusCode.BadRequest;
      return;
   }

   post.Id = GetNextPostId();

   UriTemplateMatch match =
      context.IncomingRequest.UriTemplateMatch;
   UriTemplate template = new UriTemplate("/post/{id}");
   post.Uri =
      template.BindByPosition(match.BaseUri, post.Id.ToString());

   _posts.Add(post);

   context.OutgoingResponse.SetStatusAsCreated(post.Uri);
}

Bindings, Behaviors, and Hosts

The new System.ServiceModel.WebHttpBinding class is responsible for preventing any automatic SOAP formatting for WCF messages, by specifying MessageVersion.None. It also performs the work required to connect the service to HTTP or HTTPS, similar to System.ServiceModel.BasicHttpBinding. System.ServiceModel.Description.WebHttpBehavior is where the bulk of the work is performed. The custom behavior uses the WebGet and WebInvoke attributes to make connections between HTTP requests/responses and OperationContracts. It provides the formatting and serialization implementations, as well as validation and other related work. WCF offers some helper classes to minimize the configuration impact of hooking up an endpoint that will serve "WebHttp" functionality. For most scenarios, these helper classes should be sufficient to establish a working endpoint. The primary helper is System.ServiceModel.Web.WebServiceHost, which automatically adds a WebHttpBehavior using the default settings. Creating a service using the WebServiceHost is as simple as specifying the desired binding. For example, the following three lines of code create and open a RESTful service endpoint at "http://localhost:8000/blog":

WebServiceHost host =
   new WebServiceHost(new BlogService.BlogService(),
                      new Uri("http://localhost:8000/blog"));
host.AddServiceEndpoint(typeof(BlogService.IBlogService),
                        new WebHttpBinding(), "");
host.Open();

To make things even easier, two ServiceHostFactory implementations (new in .NET 3.5, but outside the scope of this article) have been included in WCF. When hosting a service in IIS, using the WebServiceHostFactory and WebScriptServiceHostFactory will automatically configure bindings, behaviors, and endpoints using the appropriate information from the IIS metabase. The difference between the two is that WebScriptServiceHostFactory will set defaults (JSON) and create restrictions (GET and POST only) such that it "plays nice" with ASP.NET AJAX out-of-the-box, and it creates a WebScriptServiceHost object that is marked internal, meaning the only way to create one is with the factory class.

Creating a Service

To demonstrate "web programming" (REST) with WCF, I have created a simple blog engine. It has no backing store, meaning a restart of the service will wipe all existing data, it is a singleton service that is single threaded (for simplicity), and it supports simple post and comment management only. Posts and comments can be created, read, updated, or deleted—this sort of functionality is frequently referred to as CRUD (Create, Read, Update, Delete). The example demonstrates some of the concepts discussed in this article, including using the WebGet and WebInvoke attributes and the WebOperationContext class, multiple hosting options, and finally the concept of returning different serialization formats for different URIs. In the case of the last feature, returning different serialization formats, I've chosen to use a scheme where the standard URI returns the format configured for the endpoint, and appending the desired format to the end of the URI will cause the response to be rendered in the requested format. For example, the following table shows several URIs that will all retrieve the same blog post, but in varying formats:

URI Response Format
/blog/post/456 Dependant on the endpoint configuration
/blog/post/456/json JSON
/blog/post/456/xml XML
/blog/post/456/rss RSS

Formatting results as RSS is outside the scope of this article, but the included example should give a good idea of how easy WCF 3.5 makes it to return syndicated data. To run the sample with the least amount of setup, simply run the BlogServer project or application. In a browser, navigate to "http://localhost:8000/blog/posts" to see the XML response from the service.

Conclusion

Windows Communication Foundation makes impressive strides ahead in version 3.5 by offering fully integrated support for web programming. The semantics of the programming model along with out-of-the-box configuration defaults make creating and hosting "RESTful" web services very simple. WCF allows service creators to expose services using SOAP and REST, increasing their value by catering to the needs and desires of the service consumers—the customer. So, tag your service with WebGet/WebInvoke and enjoy the REST.

Download the Code

You can download the code that accompanies this article here.

Acronyms

  • REST: Representational State Transfer
  • WCF: Windows Communication Foundation
  • HTTP: Hypertext Transfer Protocol
  • ASMX: The ASP.NET implementation of Web Services—ASMX is the file extension used on the "endpoint"
  • JSON: Javascript Object Notation
  • XML: Extensible Markup Language
  • RSS: Really Simple Syndication, Rich Site Summary, or RDF Site Summary—depending on who you ask

References

  1. http://en.wikipedia.org/wiki/REST: Wikipedia entry on REST
  2. http://msdn2.microsoft.com/en-us/library/aa395208.aspx: REST and POX with WCF (3.0)
  3. http://hyperthink.net/blog: Steve Maine, Program Manager for Microsoft
  4. http://www.developer.com/net/net/article.php/3668901: A Primer to Windows Communication Foundation (3.0)
  5. http://www.developer.com/net/net/article.php/3676161: Building WCF Channels and Bindings (3.0)

About the Author

Aaron Lerch is a Software Developer and Team Lead for Interactive Intelligence, Inc. in Indianapolis, Indiana, USA. By day, he leads a team working on Windows Forms/WPF applications and by night, he dives into WCF, PowerShell, ASP.NET, and any other interesting .NET-based technologies. He keeps a blog about his development experiences at http://www.aaronlerch.com/blog.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel