ARTICLE

Create Restful WCF Service API

Posted by ashutosh k shukla Articles | WCF with C# August 30, 2010
In this article I am going to explain you how to implement restful service API using WCF 4.0 . The Created API returns XML and JSON data using WCF attribute.
Reader Level:
Download Files:
 

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. In this article I am going to explain you how to implement restful service API using WCF 4.0 . The Created API returns XML and JSON data using WCF attribute.

Normally developer scared to use WCF because lot of confusing configuration. I will try to use minimum configuration so that it will be easier to understand for us. We will develop Restful WCS API in 6 steps. So let's start now.


What is REST?

Based on Roy Fielding theory "Representational State Transfer (REST), attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."

Actually only the difference is how clients access our service. Normally, a WCF service will use SOAP, but if you build a REST service clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc). 

REST uses some common HTTP methods to insert/delete/update/retrive infromation which is below: 

a) GET -  Requests a specific representation of a resource

b) PUT - Create or update a resource with the supplied representation

c) DELETE - Deletes the specified resource

d) POST - Submits data to be processed by the identified resource 


Why and where to use REST?

Few days back i was writing a service which was suppose to access by heterogeneous language/platform/system. It can be used by iPhone, Android, Windows Mobile, .NET web application, JAVA or PHP. Using web service it was bit complex for me to expose it to everyone using uniform system. Then we decided to use REST, which was easily espoused over cloud. This was a great example which shows the capability of SIMPLE RESTful SERVICE :) .  Below is some point which will help you to understand why to use the RESTful services.

1) Less overhead (no SOAP envelope to wrap every call in)

2) Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope).

3) More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.

4) More human readable and testable (harder to test SOAP with just a browser).

5) Don't need to use XML (well you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope).

6) Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. Yes in theory SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.

Step by step guide

Generally developer scared to use WCF because lot of confusing configuration. I will try to use minimum configuration so that it will be easier to understand for us. We will develop Restful WCS API in 6 steps. So let's start now.

Step 1. First of all launch Visual Studio 2010. Click FILE->NEW->PROJECT.  

Create new "WCF Service Application" . 


image1.gif

Step 2. You can see in solution that By Default WCF service and interface file is already created. Delete By default created file as we will create our own interface and WCF service file.

image2.gif

Step 3. Now Right click on solution and create one new WCF service file. I have given name to the service file as "RestServiceImpl.svc".

image3.gif

Step 4. as I explained in starting of the article that we will be writing an API which can return data in XML and JSON format, here is the interface for that. In IRestServiceImpl , add following code.

image4.gif

In above code, we can see two different method of IRestService which is XMLData and JSONData. XMLData Returns result in XML whereas JSONData in JSON.

Step 5. Open the file RestServiceImpl.svc.cs and write following code over there..

image5.gif

Implementation of the method is same for both function but the response format would be different because of ResponseFormat of WCF 4.0 .

Step 6. Now let's move to configuration part which is the last one. There will be two basic part of the configurations file which we must have to understand...

A. <services>:

This part of the configuration file contains details about END POINT

image6.gif

B. <behaviors>:

This part contains details about service and endpoint behaviour details.

image7.gif

And that's it. Our Restful WCF service is ready for test purpose.

Now I launch the application in browser to see the result. I launch this service in IE and my URL is now http://localhost:35798/RestServiceImpl.svc . Now if I use http://localhost:35798/RestServiceImpl.svc/xml/123 URL, I get following response on the browser which an XML format and that was my task to achieve.

image8.gif

Now if I use http://localhost:35798/RestServiceImpl.svc/json/123 URL, i get following response on the browser which an XML format and that was my task to achieve.

image9.gif

Comments, suggestions and criticisms are all welcome.

Thanks
 

Login to add your contents and source code to this article
post comment
     

In step 1 you should tell us to name the project "RestService". Right? In step 3 instead of saying right-click on the solution, it is better to say right-click on the project. Right? Then say we need to add a new item and the new item is a "WCF service" file. When I read it the first time I thought you were adding a new project to the solution. Then in step 6 it will help to say that the services and behaviors will replace the behaviors; in the generated file, there is not a services section. Right? I am a beginner and I do not know hos to make it work. I downloaded the sample and when I debug it, the WCF Test Client executes but it does nothing; it does not show the application. When I build the application using your instructions in a separate project, I only get a web page with a directory listing of the project.

Posted by Sam Hobbs Jul 27, 2012

I have implemented your example and when I request either the XML or JSON I get an HTTP 400 error. Here is an excerpt from the code page. [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/{id}")] string XMLData(string id); What I am missing? Thanks, m.

Posted by mdgardipee Mar 07, 2011


This is because you haven't configured our service to expose any meta data about it. To expose a WSDL for a service we need to configure our service to provide meta information.  
 
 Please check this value in config file and make sure its true. 

<serviceMetadata httpGetEnabled="true" />

Thanks
Ashu

Posted by ashutosh k shukla Nov 23, 2010

Hi ashutosh,

This is james i was successfully done the restwcf w hat u given tat is working fine.

when i was publish and running from t he browser th en im getting fine.

if i click the a link in the browser window like
"svcutil.exe http://machine.domainname/service/myservice.svc?wsdl"
im unable to load the wsdl .

why im unable to run it using the "machinename.portno"

pls expalin !.

what is the behind for this error,

Posted by James Chowdary Nov 23, 2010

I am sure that this  error is because it can't find the endpoint. Are you hitting it using POST to the right URL under /rest? Please try Fiddler for POST call.


Thanks

Posted by ashutosh k shukla Sep 15, 2010
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.