Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » WCF » Create Restful WCF Service API

Create Restful WCF Service API

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.

Page Views : 7577
Downloads : 146
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RestService.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
ashutosh k shukla

A versatile person having 6.0 Years of IT Industry experience in software development on .NET Technology presently leading the team successfully. 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
How to lead a team successfully by Raj On August 31, 2010
Hey can you share How to lead a team successfully???? Share some tips with c-sharpcorner users.
Reply | Email | Modify 
Re: How to lead a team successfully by ashutosh k On August 31, 2010
LOL
Good question. But i think this is not right place to discuss about this. You can catch me on my email address which is ashutosh.shukla1@gmail.com . Sorry for the inconvenience.

Thanks
Ashu
Reply | Email | Modify 
Nice tutorial by none On September 11, 2010
Thx.
Reply | Email | Modify 
Oups by dang On September 15, 2010
I got that result when using http://localhost:35798/RestServiceImpl.svc/xml/123:
Service
Endpoint not found.
Reply | Email | Modify 
Re: Oups by ashutosh k On September 15, 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
Reply | Email | Modify 
Re: Re: unable to publish the metadata by James On November 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,

Reply | Email | Modify 
Re: Re: Re: unable to publish the metadata by ashutosh k On November 23, 2010

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
Reply | Email | Modify 
HTTP 400 Error when viewing either XML or JSON by mdgardipee On March 7, 2011
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.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.