http://www.developer.com/net/article.php/3825601/RESTing-with-the-Microsoft-REST-Starter-Kit.htm
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. 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: A more complete introduction can be found in the "Sources" section at the end of the article. 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: 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. My REST service is a "Self Hosted" Console application exposing three endpoints: 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. 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: Aside from the WebServiceHost2 class the server setup is boilerplate WCF. PlainXML, the Service Type, requires some more detailed exploration. 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: The WebInvoke attribute maps any 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. 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. HttpClient houses most of the client-side functionality.
Like other parts of the .NET Framework, there are two ways
to utilize the library: I'll review the Synchronous functionality first and the
cover the Asynchronous functionally later in the article.
Post returns an 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.
One other interesting feature of the Below is the same In the Async invocation the developer creates the 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.
RESTing with the Microsoft REST Starter Kit
June 22, 2009
REST Introduction
POST, GET, PUT, DELETE performing Create, Read, Update, and Delete on the Resources. Starter Kit Overview
Click here for larger image
Figure 1: REST Templates in Visual Studio
Self Hosted Service
Click here for larger image
Figure 2: Help resource in the browser.
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();
Service Type
[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)
};
}
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.HttpClient
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>();
}
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.HttpResponseMessage containing two pieces
of information.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.HttpStage
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
Post performed above, but this time using the Asynchronous Programming Model. request.Data = "My request asnyc...";
HttpContent content = HttpContentExtensions.CreateDataContract
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
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