Thursday, September 18, 2008

RESTful Application with AJAX and WCF

by S.Luann

First of all, I need to let the WCF service be exposed as RESTful. It is done by specifying attribute WebGet or WebInvoke as in following code snippets.

[OperationContract]
[WebGet(UriTemplate = "/posts")]
PostResultSet GetPosts();


[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/admin/post/{id}")]
void UpdatePost(string id, Post post);


In the second code excerption, the id in uri template is bount to the parameter in the contract implementation method. Any bound parameter should be string type.

Both WebGet and WebInvoke attributes indicate that the service accept http request and response. it is nothing to do with SOAP.


WebGet has following properties:

BodyStyle : WebMessageBodyStyle = Bare | Wrapped | WrappedRequest | WrappedResponse
RequestFormat : WebMessageFormat = Jason | Xml
UriTemplate: string

For WebInvokeAttribute, it has one more:
Method : string = "POST" | "DELETE" | "*" and so forth.

Secondly, I need access WebOperationContext in my operation contract implementation.

WebOperationContext exposed four properties:

IncomingRequest
IncomingResponse
OutgoingRequest
OutgoingResponse


List 1: access WebOperationContext
WebOperationContext context = WebOperationContext.Current;

// get query parameter
string strVal = UriMatch.QueryParameters[strName];
if(!strVal.IsNullOrEmpty(strVal))
{
Int32.TryParse(strVal, out value);
...
}

context.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;

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





Thirdly, I need to host the service and configure it up

List 2: Host a RESTful service
WebServiceHost host = new WebServiceHost(new BlogService.BlogService(),
new Uri("http://localhost:8000/blog"));
host.AddServiceEndpoint(typeof(BlogService.IBlogService),
new WebHttpBinding(), "");
host.Open();

Adding an endpoint to a service host exposes the service interface to specified protocal to access it.
Note in List 2, the service endpoint used WebHttpBinding.


Used .Net API namespaces and classes
System.ServiceModel.BasicHttpBinding
System.ServiceModel.Description.WebHttpBehavior
WebScriptServiceHostFactory
System.Net.HttpStatusCode.BadRequest
WebOperationContext
UriTemplate
WebServiceHost
WebHttpBinding




Reference
1. Aaron Lerch, Creating RESTful Web Services with Windows Communication Foundation
http://www.developer.com/net/article.php/10916_3695436_1

No comments: