Monday, April 4, 2011

ReST Application using WCF

This article is about creating a simple ReST(Representational State Transfer) application using WCF. Using ReST model of communication, web services can be invoked without the WSDL.

Let us go through an example on how to develop a ReST application


1) Create a WCF application in VS 2008
(File -> New project-> Select "WCF Service Application" (Under Visual C#, Web))
Visual Studio will create service file (Service1.svc and IService1.cs)

2) Add reference to "System.ServiceModel.Web" ( This is required for "WebGet" Attribute that is used in interface method definition )

Let us reuse IService.cs for our example.

3) Create a new method definition in IService1 as given below

[WebGet(UriTemplate = "users/{username}")]
[OperationContract]
string GetFullName(string username);

4) Implement the interface method in Service1.svc as given below

public string GetFullName(string username)
{
return "Hello " + username;
}

5)In web.config make below 2 changes

 a) Remove the existing endpoint and add the new endpoint

<endpoint address="" behaviorconfiguration="webHttp" binding="webHttpBinding" contract="RestTestApp.IService1">
<identity>
<dns value="localhost">
</identity>
</endpoint>

 b) Include endpoint behavior for webHttp. This should be inside tag

<endpointbehaviors>
<behavior name="webHttp">
<webhttp>
</behavior>
</endpointbehaviors>


6)The development of ReST application is complete! Run the application.

Navigate to -
http://localhost:{Port if using Development server}/UserService.svc/users/test

This will return an xml

With ReST model , we are now able to access the service without passing the parameters in XML (SOAP). The service can be accessed and executed using a simple http webrequest.

We will look at how to consume this ReST application in later articles.

Till then, happy coding.

No comments: