Monday, February 1, 2010

Simple 5 steps to expose WCF services using REST style

Introduction
Video of this article
Step 1:- Create your WCF service project.
Step 2:- Make changes to the web.config files
Step 3:- Decorate your methods with ‘WebInvoke’ attribute.
Step 4:- Run your program.

Introduction


WCF Rest Services are nothing but simple WCF Services with added functionality
of consuming WCF service in a Restful manner. For instance if you had a order
web service that you built in WCF, instead of consuming them through heavy SOAP
implementation and ASMX, you can use the WCF Rest functionality to consume the
service by using simple HTTP verbs like post and get.
So rather than passing complicated SOAP message to the below link to get a order detail http://localhost/order.svc

We can now use REST style to get order as shown in the below URL
http://localhost/order.svc/GetOrder/100234

In this article we demonstrate the 4 important steps to enable your WCF service as a REST service.

Video of this article

In case you are lazy like me you can download the video of this article in MP4 format from http://tinyurl.com/y8j4jjb .

Step 1:- Create your WCF service project.

The first step is to create your WCF service. So click on new website and select WCF service template.



Step 2:- Make changes to the web.config files

The next step is to make changes in the Web.config files to ensure that its uses the HTTP verbs like post and get. So open the web.config file of your WCF project and change the binding to ‘webHttpBinding’ as shown in the below code snippet.
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="WebBehavior1">

We also need to insert the ‘endpointBehaviors’ tag with ‘webHttp’ tag in the behavior tag as shown in the below code snippet.
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior1">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>



Step 3:- Decorate your methods with ‘WebInvoke’ attribute.

The next step is to decorate the function / method with ‘WebInvoke’ attribute as shown below. So decorate your function which you want to expose through REST using the ‘WebInvoke’ and specify the HTTP method which this function will accept, currently its ‘GET’.

We have also specified what kind of URI template will be used with the function. Currently we have specified the format as ‘Getdata/{value}’. In other words we can pass data as ‘GetData/1’, GetData/2’ etc.

using System.ServiceModel.Web;
[OperationContract]
[WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetData/{value}")]
string GetData(string value);

Step 4:- Run your program.

Now run your program with URL as ‘http://localhost/WcfService3/Service.svc/GetData/12’ as shown in the below figure and it will display the data in the XML format as shown in the below figure.

1 comment:

Anonymous said...

nice post. thanks.