www.developer.com/net/article.php/3825601
|
By Jeffrey Juday June 22, 2009 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 IntroductionA 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. Starter Kit OverviewThe 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. Self Hosted ServiceMy 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: 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. Service TypeI 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 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. HttpClientThings 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:
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.
HttpStageOne other interesting feature of the 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");
}
}
Async Programming ModelBelow is the same request.Data = "My request asnyc...";
HttpContent content = HttpContentExtensions.CreateDataContract
In the Async invocation the developer creates the ConclusionREST 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. SourcesProjet 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 |