RESTing with the Microsoft REST Starter Kit

When it comes to interoperability, Internet standards rule. Representational State Transfer (REST) is a Web Service construction philosophy built on some of the original ideas behind sharing documents on the web and it's emerging as a popular way to implement Web Services inside the firewall.

Like other software companies, Microsoft has adopted many Internet standards in their products. It was unsurprising to hear Microsoft embrace REST; first by adding more "RESTful" features to WCF, imbuing products like Azure with a REST philosophy, and then upping the ante with the "Microsoft REST Starter Kit". I'm going show how you can more easily embrace REST using the Microsoft REST Starter Kit.

REST Introduction

A complete introduction to REST is beyond the scope of this article. So I'll be brief. Most REST introductions begin with the "REST Philosophy" and then move into how the technology implements the philosophy. I think it's important to immerse yourself in the philosophy if you think you want to build a "production" REST Web Service, but if you're simply tinkering with technology think of REST as being three things:

  • Web Services, the part of the Internet consumed by software rather than viewed by humans.
  • Resources expressed as URLs, for example, http://www.RESTService.com/ResourceHere.
  • HTTP verbs POST, GET, PUT, DELETE performing Create, Read, Update, and Delete on the Resources.

A more complete introduction can be found in the "Sources" section at the end of the article.

Starter Kit Overview

The mission of the .NET Framework is to make Windows programming available to the widest possible audience of developers. As I mentioned earlier making REST easier in WCF was the first step, now it looks like Microsoft is circling back with more REST features.

You'll find the REST Starter Kit Preview 2 on Codeplex http://weblogs.asp.net/cibrax/archive/2009/03/13/ httpclient-in-the-wcf-rest-starter-kit-preview-2.aspx. The Kit is built on top of WCF, so if you have WCF experience, you'll be familiar with many of the kit's conventions. The kit also includes all of the source code files behind the Starter Kit components.

The REST Starter Kit works with Visual Studio 2008. Once installed you'll notice a new set of templates highlighted in the picture below:



Click here for larger image

Figure 1: REST Templates in Visual Studio

Like many of the Visual Studio templates, the REST templates give you a simple working application shell that you fill with your own code. Each template is a REST service with a different flavor. The templates give you a quick way to "REST" server-side, client-side will require some coding. Rather than leveraging the templates, I wanted to show that you can use the Kit outside of the templates to build your server side parts.

Self Hosted Service

My REST service is a "Self Hosted" Console application exposing three endpoints:

  • http://localhost:8000/TestServiceHost/GetData
  • http://localhost:8000/TestServiceHost/DoWork
  • http://localhost:8000/TestServiceHost/Help

The Uri ending with "Help" is automatically supplied by the REST Starter Kit components and best viewed by a Web Browser since the service response is in HTML. Below is part of the "Help" resource's HTML rendered in the browser.



Click here for larger image

Figure 2: Help resource in the browser.

Microsoft.ServiceModel.Web contains much of the Starter Kit Server side functionality, so references to it have been added to the project.

The host setup code appears below:

  WebServiceHost2 host;
  Uri[] baseAddresses = new Uri[1];
  
  Console.WriteLine("Initiating host communication...");
  
  baseAddresses[0] = new Uri("http://localhost:8000/TestServiceHost");
  
  host = new WebServiceHost2(typeof(PlainXML), false, baseAddresses);
  
  host.Open();

Aside from the WebServiceHost2 class the server setup is boilerplate WCF. PlainXML, the Service Type, requires some more detailed exploration.

RESTing with the Microsoft REST Starter Kit

Service Type

I copied most of the PlainXML Service Type code from an application created from the "HTTP Plain XML WCF Service" template. I only made changes to some of the hosting attributes on the Service Type. Code implementing an HTTP POST to http:// localhost:8000/TestServiceHost/DoWork appears below:

  [WebHelp(Comment = "Sample description for DoWork")]
  [WebInvoke(UriTemplate = "DoWork")]
  [OperationContract]
  public SampleResponseBody DoWork(SampleRequestBody request)
  {
      return new SampleResponseBody()
      {
          Value = String.Format("Sample DoWork response: '{0}'", request.Data)
      };
  }

The WebInvoke attribute maps any POST to the "DoWork" resource to the code above and WebHelp controls some of what is displayed by a GET to the "Help" resource. GetData follows a similar pattern as POST, only the attributes and returned information differ.

Like much of WCF, the REST Starter Kit relies on DataContractSerialization. So when the POST executes the runtime Deserializes to a SampleRequestBody object and then Serializes a SampleResponseBody before transmission to the Client.

HttpClient

Things are a little more exciting on the Client side. Main parts of the Client side code appear below with Console Writeline statements removed for readability.

  string baseUri = "http://localhost:8000/TestServiceHost/";
  HttpClient http = new HttpClient(baseUri);
  SampleRequestBody request = new SampleRequestBody();
  HttpResponseMessage resp;
  SampleResponseBody respBody = null;
  
  http.Stages.Add(new StageProcessingTest());
  
  request.Data = "My request...";
  
  resp = http.Post("DoWork", 
           HttpContentExtensions.CreateDataContract<SAMPLEREQUESTBODY>(request));
  
  if (resp.StatusCode == System.Net.HttpStatusCode.OK)
  {
      respBody = resp.Content.ReadAsDataContract<SAMPLERESPONSEBODY>();
  }

HttpClient houses most of the client-side functionality. Like other parts of the .NET Framework, there are two ways to utilize the library:

  • Synchronously where the thread blocks until the call returns
  • Asynchronously where the thread executes elsewhere and the .NET Runtime makes a callback to a supplied delegate when the request is completed or fails.

I'll review the Synchronous functionality first and the cover the Asynchronous functionally later in the article.

Post, Get, Delete, and Put are all synchronous methods on the HttpClient object. I do a Post in the example, but the other operations work in a similar fashion.

Post returns an HttpResponseMessage containing two pieces of information.

A status of the HTTP operation, so rather than decoding each HTTP status code to determine success or failure the Starter Kit does the decoding for you. If you do want to look at the nitty-gritty response codes the response message includes the details.

Data is returned in the Content Property. HttpContentExtensions provides functions to push the data into .NET objects or manipulate the raw byte stream. In the example, I'm Deserializing the content into a SampleResponseBody function.

RESTing with the Microsoft REST Starter Kit

HttpStage

One other interesting feature of the HttpClient is the HttpStage Collection. HttpStage collection acts as a sort of pipeline for the HttpClient allowing things like caching data or performing additional operations on the HttpRequestMesage or HttpResponseMessage. Below is the StageProcessingTest class implementation.

  class StageProcessingTest : HttpProcessingStage
  {
      public override void ProcessRequest(HttpRequestMessage request)
      {
          Console.WriteLine("Request stage executed...");
      }
  
      public override void ProcessResponse(HttpResponseMessage response)
      {
          SampleResponseBody respBody = null;
  
          response.Content.LoadIntoBuffer();
  
          respBody = 
response.Content.ReadAsDataContract<SAMPLERESPONSEBODY>();
  
          Console.WriteLine( "Response stage executed... " + 
             respBody.Value + " added something");
          
      }
  }

HttpProcessingStage, the base class for StageProcessingTest, is a specialized implementation of HttpStage.

Async Programming Model

Below is the same Post performed above, but this time using the Asynchronous Programming Model.

      request.Data = "My request asnyc...";
      HttpContent content = HttpContentExtensions.CreateDataContract(request);
      Uri doWork = new Uri("DoWork", UriKind.Relative);
      HttpRequestMessage reqMessage = new HttpRequestMessage("POST", doWork, content);
  
      http.SendCompleted += AsnycSendComplete;
  
      http.SendAsync(reqMessage);
  
  
  static void AsnycSendComplete(object sender, SendCompletedEventArgs eSendCompletedEventArgs)
  {
      SampleResponseBody respBody = null;
  
      respBody = eSendCompletedEventArgs.Response.Content.ReadAsDataContract();
  
      Console.WriteLine("AsnycSendComplete " + respBody.Value);
  }

In the Async invocation the developer creates the HttpRequestMessage, supplies a delegate callback function, in the example "AsyncSendComplete", and then calls SendAsync. Like the synchronous functions a single class, in this case the SendCompletedEventArgs, returns the Content and the status of the invocation.

Conclusion

REST has become a fixture in the Microsoft product line. First becoming part of WCF, then part of some strategic products, and finally settling in the Microsoft REST Starter Kit. An intuitive set of classes shipping with the Starter Kit, make REST construction accessible to any .NET developer.

Sources

Projet Source Code
.NET Framework Conceptual Overview
HttpClient in REST starter Kit Preview 2
REST in Windows Communication Foundation
Introduction to the HttpClient
http://en.wikipedia.org/wiki/Representational_State_Transfer


About the Author

Jeffrey Juday

Jeff is a software developer specializing in enterprise application integration solutions utilizing BizTalk, SharePoint, WCF, WF, and SQL Server. Jeff has been developing software with Microsoft tools for more than 15 years in a variety of industries including: military, manufacturing, financial services, management consulting, and computer security. Jeff is a Microsoft BizTalk MVP. Jeff spends his spare time with his wife Sherrill and daughter Alexandra.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds