You are on page 1of 11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject

Sign up for our free weekly Web Developer


11,177,812
Newsletter.
members 80,865 online

julvertvargas

126 Sign out

home

articles

quick answers

discussions

features

community

help

Searchforarticles,questions,tips

Articles Platforms, Frameworks & Libraries Windows Communication Foundation General

Create and Consume RESTFul Service in .NET Framework


4.0
Arthanarieaswaran, 23 Mar 2012

CPOL

Rate:

4.78 61 votes

Info
First Posted

16 Sep 2011

Views

259,785

Downloads

11,267

Bookmarked 190 times

Explains the basics of REST services and create & consume RESTful service in ASP.NET

Download demo 15.43 KB

About This
I am writing this article to explain creating & consuming RESTFul service using .NET Framework 4.0.

What is Web Services, WCF?


Web Service
Web Service is like components on a Web Server, client application uses this service by calling Hypertext Transfer
Protocol (HTTP) requests across the Web. Using ASP.NET, we can create custom Web Services, and call these
services from any client applications.
Web Services are platform, programming language independent; they send as well as receive data using Simple
Object Access Protocol (SOAP) messages.

WCF
Windows Communication Foundation WCF is Microsofts combined programming model for building
serviceoriented architecture (SOA). Using this,thedeveloper can build a secure, reliable, transacted solutions
across platforms.
WCF supports concentrated computing where services have isolated consumers. Clients can consume multiple
services as well as services can be consumed by multiple clients.
For creating basic application in WCF, please refer to the article Introduction of Window Communication
Foundation.
Web Services
Web services were developed for
building applications that send and
receive messages by using the Simple
Object Access Protocol SOAP over
HTTP. The structure of the messages
can be defined using an XML Schema,
and a tool is provided to facilitate
serializing the messages to and from
.NET Framework objects. The
technology can automatically generate
metadata to describe Web services in
the Web Services Description
Language WSDL

WCF Services
WCF services were developed for building applications to
send and receive messing by using many formats and
conveyed by using any transport protocol. Simple Object
Access Protocol SOAP is used by default format.The
structure of the messages can be defined using an XML
Schema, and there are various options for serializing the
messages to and from .NET Framework objects. WCF can
automatically generate metadata to describe applications
built using the technology in WSDL, and it also provides a
tool for generating clients for those applications from the
WSDL.
Support for sending messages using not only HTTP, but also

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

1/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
TCP and other network protocols. The ability to switch
message protocols with minimal effort. Support for hosting
services on hosts other than a Web server. Builtin support
for the latest Web services standards SOAP 1.2 and WS*
and the ability to easily support new ones. Support for
security, transactions and reliability. Support for sending
messages using formats other than SOAP.

XmlSerializer

DataContractSerializer

ASP.NET relies on the XmlSerializer


to translate data represented by .NET
Framework types to XML for
transmission to or from a service and
to translate data received as XML into
.NET Framework objects. Defining the
complex data types that an ASP.NET
service is to use requires the definition
of .NET Framework classes that the
XmlSerializercan serialize to and
from XML.

The DataContractAttributesignifies that zero or more


of a types fields or properties are to be serialized, while the
DataMemberAttributeindicates that a particular field or
property is to be serialized. The DataContractAttribute
can be applied to a class or structure. The
DataMemberAttributecan be applied to a field or a
property, and the fields and properties to which the
attribute is applied can be either publicor private.
Instances of types that have the DataContractAttribute
applied to them are referred to as data contracts in WCF.
They are serialized into XML using
DataContractSerializer.

The DataContractSerializer,
DataContractAttributeand DataMemberAttribute
provide very little control over how a type is represented in
The XmlSerializerand the
XML. You can only specify the namespaces and names used
attributes of the
to represent the type and its fields or properties in the XML,
System.Xml.Serialization
and the sequence in which the fields and properties appear
namespace are designed to allow you
in the XML. Everything else about the structure of the XML
to map .NET Framework types to any
used to represent the .NET type is determined by the
valid type defined in XML Schema, and
DataContractSerializer. By not permitting much
so they provide for very precise control
control over how a type is to be represented in XML, the
over how a type is represented in XML.
serialization process becomes highly predictable for the
DataContractSerializer, and, thereby, easier to
optimize.
Lesser performance compared with
WCF DataContractSerializer.

A practical benefit of the design of the


DataContractSerializeris better performance,
approximately ten percent better performance.

The attributes for use with the


XmlSerializerdo not indicate
which fields or properties of the type
are serialized into XML.

DataMemberAttributefor use with the


DataContractSerializershows explicitly which fields or
properties are serialized. Therefore, data contracts are
explicit contracts about the structure of the data that an
application is to send and receive.

The XmlSerializercan only


translate the publicmembers of a
.NET object into XML.

The DataContractSerializercan translate the


members of objects into XML regardless of the access
modifiers of those members.

Instances of collection classes can be


serialized into XML only if the classes
implement either the IEnumerable
or ICollectioninterface.

The DataContractSerializeris much more likely to be


able to serialize the instances of any preexisting .NET type
into XML without having to either modify the definition of
the type or develop a wrapper for it.

Classes that implement the


IDictionaryinterface, such as
Hashtable, cannot be serialized into
XML.

It can translate into XML types like Hashtablethat


implement the IDictionaryinterface.

XmlSerializerdoes not support


versioning.

The DataContractSerializerincorporates some


support for versioning.

XmlSerializerserializes a type by
default is semantically identical to the
XML.

DataContractSerializerserializes a type, provided the


namespace for the XML is explicitly defined.

What is REST & RESTful?


Representational State Transfer REST is introduced by Roy Fielding on 2000; it is an architectural style of
largescale networked software that takes advantage of the technologies and protocols of the World Wide Web.
REST illustrate how concentrated data objects, or resources, can be defined and addressed, stressing the easy

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

2/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
exchange of information and scalability.
In 2000, Roy Fielding, one of the primary authors of the HTTP specification, wrote a doctoral dissertation titled
Architectural Styles and the Design of Networkbased Software Architectures.
REST, an architectural style for building distributed hypermedia driven applications, involves building Resource
Oriented Architecture (ROA) by defining resources that implement uniform interfaces using standard HTTP verbs
GET, POST, PUT, and DELETE, and that can be located/identified by a Uniform Resource Identifier (URI).
REST is not tied to any particular technology or platform its simply a way to design things to work like the Web.
People often refer to services that follow this philosophy as RESTful services. WCF Services which is developed
using REST architectural style is known as RESTFul Services.
WCF Services

RESTFul Services

Endpoints have to create for each network


protocol

It can be connect over "Web" with HTTP


request/response messages.

It works based on the Remote Procedural


Call RPC

It is working with HTTP's uniform interface

Service Reference has to add in the client


applications

No need to add the service reference in the client


applications

What is the REST Starter Kit?


The WCF REST Starter Kit is a set of .NET Framework classes and Visual Studio features and templates that
enable users to create and access RESTstyle Windows Communication Foundation WCF services. These services
are based on the WCF web programming model available in .NET 3.5 SP1. The starter kit also contains the full
source code for all features, detailed code samples, and unit tests.

Creating basic RESTFul Service


Step 1
Create a new WCF project using VS2010.
Language

Visual C# or Visual Basic

Target Framework

.NET Framework 4

Installed Templates

WCF

Template

WCF Service Application

Name

RESTFulDemo

Step 2
http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

3/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
Delete the existing IService1.cs & Service1.svc files and create two new files, IRESTService.cs & RESTService.cs.

Step 3
Create the person entity in the IService.cs it can be created separately and write asimple member for this entity.
For DataContractSerializationdecorate this class and member with DataContract& DataMember
attributes. See the code below:
Collapse | Copy Code

[DataContract]
publicclassPerson
{
[DataMember]
publicstringID;
[DataMember]
publicstringName;
[DataMember]
publicstringAge;
}

Personclass and its members decorated with [DataContract] & [DataMember] using
System.Runtime.Serializationnamespace.
[DataContract] An entity class which can be DataContractSerializableover the network.
[Datamember] Only decorated with [Datamember] property can be serializable & also property of the
class must be decorated with [DataContract]

Step 4
Create methods in IRESTService class and interface decorated with [ServiceContract] & its members
decorated with [OperationContrat] using System.ServiceModelnamespace.
Collapse | Copy Code

[ServiceContract]
publicinterfaceIRestSerivce
{
[OperationContract]
PersonCreatePerson(PersoncreatePerson);
[OperationContract]
List<person>GetAllPerson();
[OperationContract]
PersonGetAPerson(stringid);
[OperationContract]
PersonUpdatePerson(stringid,PersonupdatePerson);
[OperationContract]
voidDeletePerson(stringid);
}

[ServiceContract] A service contract exposes class or interface to the client applications, which may
contain one or more [OperationContract] methods.
[OperationContract] Indicates that a method defines an operation that is part of a service contract in
an application, i.e., only the method decorated with [OperationContract] is visible for WCF client
application and class of this method must be decorated with [ServiceContract].

Step 5
Up to this level, code is similar to that normal WCF services, RESTful services works under HTTP protocol, as there
is two important attributes WebGet & WebInvoke System.ServiceModel.Webnamespace has to include for
making this application as RESTful service.

WebGet and WebInvoke


http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

4/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
WebGet operation is logically receiving the information from a service operation & it can be called by the REST
programming model. The WebGet attribute is applied to a service operation in addition to the
OperationContract and associates the operation with a UriTemplateas well as the HTTP protocol Get verb.
WebInvoke operation logically raises a service option & it can be called by the REST programming model. The
WebInvoke attribute is applied to a service operation in addition to the OperationContract and associates the
operation with a UriTemplateas well as an underlying transport verb that represents an invocation for
example, HTTP POST, PUT, or DELETE. WebInvoke has a property called Method, it allows specifying different
types of HTTP methods POST, PUTor DELETE, and by default Methodis POST.
Collapse | Copy Code

[ServiceContract]
publicinterfaceIRestSerivce
{
//POSToperation
[OperationContract]
[WebInvoke(UriTemplate="",Method="POST")]
PersonCreatePerson(PersoncreatePerson);
//GetOperation
[OperationContract]
[WebGet(UriTemplate="")]
List<person>GetAllPerson();
[OperationContract]
[WebGet(UriTemplate="{id}")]
PersonGetAPerson(stringid);
//PUTOperation
[OperationContract]
[WebInvoke(UriTemplate="{id}",Method="PUT")]
PersonUpdatePerson(stringid,PersonupdatePerson);
//DELETEOperation
[OperationContract]
[WebInvoke(UriTemplate="{id}",Method="DELETE")]
voidDeletePerson(stringid);
}

Please see the modified code for IRESTService interface, WebGet & WebInvoke attributes decorates for
methods available in the IRESTService interface.
Collapse | Copy Code

PersonCreatePerson(PersoncreatePerson);
//Itisbasicallyinsertoperation,soWebInvokeHTTPPOSTisused
List<person>GetAllPerson();
PersonGetAPerson(stringid);
//Thesetwomethodsretrievetheinformation,soWebGet(HTTPGet)isused
PersonUpdatePerson(stringid,PersonupdatePerson);
//Thismethodupdatestheavailableinformation,soWebInvokeHTTPPUTisused
voidDeletePerson(stringid);
//Thismethoddeletestheavailableinformation,
//soWebInvokeHTTPDELETEisused

Step 6
Implement the IRESTService in the RESTService class and complete the business requirements. Please see
the sample code below:
Collapse | Copy Code

publicclassRestSerivce:IRestSerivce
{
List<person>persons=newList<person>();
intpersonCount=0;
publicPersonCreatePerson(PersoncreatePerson)
{
createPerson.ID=(++personCount).ToString();
persons.Add(createPerson);
returncreatePerson;
}

publicList<Person>GetAllPerson()
{
returnpersons.ToList();
}
publicPersonGetAPerson(stringid)
{
returnpersons.FirstOrDefault(e=>e.ID.Equals(id));
}
publicPersonUpdatePerson(stringid,PersonupdatePerson)
{
Personp=persons.FirstOrDefault(e=>e.ID.Equals(id));

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

5/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
p.Name=updatePerson.Name;
p.Age=updatePerson.Age;
returnp;
}
publicvoidDeletePerson(stringid)
{
persons.RemoveAll(e=>e.ID.Equals(id));
}
}

Step 7
We have to make this service able to be run in ASP.NET compatibility mode, for this
AspNetCompatibilityRequirements attributes have to decorate with the RESTService class.
Collapse | Copy Code

[AspNetCompatibilityRequirements

(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
publicclassRESTSerivce:IRestSerivce
{
//CodeImplementation
//......
//......
}

In the above RESTService class additionally decorated with ServiceBehavior attribute, it specifies internal
behavior of a service operation.

Step 8
For using this RESTFul service application, this service has to host. So we need to be done below modification for
running the RESTService.

Modifying the Web.Cogfig File


Remove all the code inside the <system.servicemodel> tag and insert the code below:
Collapse | Copy Code

<serviceHostingEnvironmentaspNetCompatibilityEnabled="true">
</serviceHostingEnvironment>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpointname=""helpEnabled="true"

automaticFormatSelectionEnabled="true"></standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>

<serviceHostingEnvironment>tag helps to run the applications in ASP.NET compatibility mode.


<standardEndpoints> tag helps to get WebHelp for the RESTFul application.

Add Global.asax File


We can host RESTFul services using Global.asax file using the below code:
Collapse | Copy Code

RouteTable.Routes.Add(newServiceRoute

("RestService",newWebServiceHostFactory(),typeof(RESTSerivce)));

Step 9
Run the RESTFulDemo application, it will be open in the explorer and address bar contain the base address of
RESTFulDemo service.
http://localhost:XXXX/
Type the Routingprefix name RestService string value given in the global.asax file.
http://localhost:XXXX/RestService It is basically URI of the Getoperation.

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

6/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject

http://localhost:XXXX/restservice/help Itdisplays the help content for RESTFulDemo service.

Still we saw about creating and hosting the RESTFul services, next we have to consume this service, therefore we
will see basic application to consume this RESTFulDemo service.

Consuming RESTFul Service


Step 1
Add a new console application to RESTFulDemosolution.
Language

Visual C# or Visual Basic

Target Framework

.NET Framework 4

Installed Templates

WCF

Template

Console Application

Name

RESTClient

Step 2
Collapse | Copy Code

do
{
try
{
stringcontent;
Console.WriteLine("EnterMethod:");
stringMethod=Console.ReadLine();
Console.WriteLine("EnterURI:");
stringuri=Console.ReadLine();
HttpWebRequestreq=WebRequest.Create(uri)asHttpWebRequest;
req.KeepAlive=false;
req.Method=Method.ToUpper();
if(("POST,PUT").Split(',').Contains(Method.ToUpper()))
{
Console.WriteLine("EnterXMLFilePath:");
stringFilePath=Console.ReadLine();

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

7/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
content=(File.OpenText(@FilePath)).ReadToEnd();
byte[]buffer=Encoding.ASCII.GetBytes(content);
req.ContentLength=buffer.Length;
req.ContentType="text/xml";
StreamPostData=req.GetRequestStream();
PostData.Write(buffer,0,buffer.Length);
PostData.Close();
}
HttpWebResponseresp=req.GetResponse()asHttpWebResponse;
Encodingenc=System.Text.Encoding.GetEncoding(1252);
StreamReaderloResponseStream=
newStreamReader(resp.GetResponseStream(),enc);
stringResponse=loResponseStream.ReadToEnd();
loResponseStream.Close();
resp.Close();
Console.WriteLine(Response);
}
catch(Exceptionex)
{
Console.WriteLine(ex.Message.ToString());
}
Console.WriteLine();
Console.WriteLine("Doyouwanttocontinue?");
}while(Console.ReadLine().ToUpper()=="Y");

Step 3
Before running the RESTFulDemoapplication, set multiple startup projects. Please see the below image:

RUN the application. It will run theRESTFulDemoservice as well as RESTClient console application.

HTTP GET Operation


Enter Method:

Get

Enter URI:

http://localhost:XXXX/restservice

It gives the XML output in the console screen.

HTTP POST Operation


Enter Method:

Post

Enter URI:

http://localhost:XXXX/restservice

Enter XML File Path:

<enter input xml file path>

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

8/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject

This operation createsanew person entity in the service, it can be seen in the browser by HTTP Getoperation.
Article
Browse Code
Stats
Revisions 3
Alternatives
Comments 120

Add your own


alternative version

In the above screen, call the URI http://localhost:XXXX/restservice/1, URI ends with person ID 1. It calls the
service operation.
Tagged as

Collapse | Copy Code

[OperationContract]
C#
[WebGet(UriTemplate="{id}")]
PersonGetAPerson(stringid);
ASP.NET
VisualStudio

So it retrieves the person with ID 1.


WCF

Beginner
Please refer to the attached
project for detailed code.
VS2010

Fiddler tool is more useful to test the RESTFul services.


REST

Conclusion
I hope this article helpsRelated
youtoArticles
understand basic concept of RESTFul and that the reader is able tocode to create
& consume RESTFul service. Please let me know your valuable comments.

References
1.
2.
3.
4.
5.

A Beginner's Tutorial
for Understanding
Windows
Communication
Foundation WCF

http://msdn.microsoft.com/enus/library/aa738737.aspx
Create RESTful WCF
Service API: Step By
http://msdn.microsoft.com/enus/netframework/dd547388
Step Guide
http://msdn.microsoft.com/enus/library/dd203052.aspx
http://msdn.microsoft.com/enus/library/system.servicemodel.web.webinvokeattribute.aspx
A Beginner's Tutorial
on Creating WCF
http://msdn.microsoft.com/enus/library/system.servicemodel.web.webgetattribute.aspx

License

REST Services

A Beginner's Tutorial
for Creating WCF
Go to top
Data Services

a REST
This article, along withCreate
any associated
source code and files, is licensed under The Code Project Open License
service with WCF
CPOL

Share

and consume it
using jQuery

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

9/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
EMAIL

About the Author

Arthanarieaswaran
Technical Lead
India
Artha is a Technical Lead in Windows Phone, WPF [MVVM, PRISM], ASP.NET [MVC 3.0 & 4.0], C#.NET, VB.NET and
ASP.

Windows Phone
Windows Phone Apps
Microsoft Developer Network
Basic Game Code With MVVM and Local Database Sample
Basic WPF Code With MVVM and PRISM MEF DI Container
Creating Single Page Application using Hot Towel Template

Published Tools in Visual Studio Galleries


Code Compiler
Windows Phone Local Database

Published Source Codes in CodePlex


Code Compiler
Windows Phone Local Database

Microsoft Virtual Academy Profile


Arthanarieaswaran Completed Courses

Published Articles in Code Project


Arthanarieaswaran Code Project Articles

Microsoft Certified Professional Developer MCPD Microsoft ASP.NET Developer 3.5 070564, 070536, 070562,
070 315

Comments and Discussions

Add a Comment or Question

Search Comments

Profile popupsSpacing Relaxed

Noise Medium

Layout Normal

Go
Per page 25

Update

First Prev Next

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

10/11

26/1/2015

CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
pass input without XML file

30Oct14 0:26

saqib_dotnet

Re: pass input without XML file

3Nov14 0:07

Arthanarieaswaran

Re: pass input without XML file

saqib_dotnet

22Nov14 22:35

405 Error when using PUT or DELETE on IIS, POST and GET is
fine, though

Member 11112768

28Oct14 16:42

Excellent Article!

Member 11112768

27Oct14 22:39

How to send response in the form of JSON

adapts

30Apr14 13:35

Re: How to send response in the form of JSON

Arthanarieaswaran

30Apr14 19:40

Several Questions and Suggestions

jroughgarden

2Apr14 16:11

Type 'ServiceRoute' is not defined

Ed_lon

Re: Type 'ServiceRoute' is not defined

12Feb14 5:21

Rapsy Tree

Re: Getting error


Re: Getting error
Re: Getting error
Really Helpful.. Great Work
Re: Really Helpful.. Great Work
Excellent Article.
Re: Excellent Article.
Great article A related question
Re: Great article A related question

Re: Vote
In depth comparison
Re: In depth comparison

Last Visit: 1Jan00 0:00 Last Update: 26Jan15 7:04


Question

13Feb14 5:45

Rapsy Tree

13Feb14 8:02

Jaswanth Reddy

13Mar14 2:55

yog240

26Dec13 4:01

Arthanarieaswaran

26Dec13 10:01

Steve Bangalore

21Nov13 16:43

Arthanarieaswaran

21Nov13 22:18

SimbarasheM

31Oct13 12:43
4Nov13 22:46
5Nov13 1:02

SimbarasheM

Vote

Suggestion

Arthanarieaswaran

Arthanarieaswaran

Re: Great article A related question

News

19Sep14 3:34

KaizerVVV

Getting error

General

27Mar14 20:54

Swarup Batabyal

26Oct13 8:07

Arthanarieaswaran

29Oct13 22:22

Hiteshforu2007

16Sep13 8:49

Arthanarieaswaran

16Sep13 23:44

Refresh
Bug

Answer

Joke

1 2 3 4 5 Next
Rant

Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile


Web04 | 2.8.150123.1 | Last Updated 23 Mar 2012

Seleccionar idioma

Layout: fixed | fluid

http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor

Article Copyright 2011 by Arthanarieaswaran


Everything else Copyright CodeProject, 19992015

11/11

You might also like