Professional Documents
Culture Documents
CreateandConsumeRESTFulServicein.NETFramework4.0CodeProject
julvertvargas
home
articles
quick answers
discussions
features
community
help
Searchforarticles,questions,tips
CPOL
Rate:
4.78 61 votes
Info
First Posted
16 Sep 2011
Views
259,785
Downloads
11,267
Explains the basics of REST services and create & consume RESTful service in ASP.NET
About This
I am writing this article to explain creating & consuming RESTFul service using .NET Framework 4.0.
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
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.
XmlSerializerserializes a type by
default is semantically identical to the
XML.
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
Target Framework
.NET Framework 4
Installed Templates
WCF
Template
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.
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.
<serviceHostingEnvironmentaspNetCompatibilityEnabled="true">
</serviceHostingEnvironment>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpointname=""helpEnabled="true"
automaticFormatSelectionEnabled="true"></standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
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
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.
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.
Get
Enter URI:
http://localhost:XXXX/restservice
Post
Enter URI:
http://localhost:XXXX/restservice
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
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
[OperationContract]
C#
[WebGet(UriTemplate="{id}")]
PersonGetAPerson(stringid);
ASP.NET
VisualStudio
Beginner
Please refer to the attached
project for detailed code.
VS2010
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
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
Microsoft Certified Professional Developer MCPD Microsoft ASP.NET Developer 3.5 070564, 070536, 070562,
070 315
Search Comments
Noise Medium
Layout Normal
Go
Per page 25
Update
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
3Nov14 0:07
Arthanarieaswaran
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
adapts
30Apr14 13:35
Arthanarieaswaran
30Apr14 19:40
jroughgarden
2Apr14 16:11
Ed_lon
12Feb14 5:21
Rapsy Tree
Re: Vote
In depth comparison
Re: In depth comparison
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
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.
Seleccionar idioma
http://www.codeproject.com/Articles/255684/CreateandConsumeRESTFulServiceinNETFramewor
11/11