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
Page 3 of 3