How To Add Ssl To Restful Service
- Download demo - 15.43 KB
Most This
I am writing this commodity 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 Spider web. Using ASP.Cyberspace, we tin can create custom Web Services, and call these services from any client applications.
Web Services are platform, programming language independent; they send likewise as receive data using Simple Object Access Protocol (Lather) messages.
WCF
Windows Communication Foundation (WCF) is Microsoft's combined programming model for building service-oriented architecture (SOA). Using this, the programmer can build a secure, reliable, transacted solutions across platforms.
WCF supports concentrated computing where services have isolated consumers. Clients tin consume multiple services as well as services tin can be consumed by multiple clients.
For creating basic awarding in WCF, delight refer to the article "Introduction of Window Communication Foundation".
Web Services | WCF 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 tin be defined using an XML Schema, and a tool is provided to facilitate serializing the messages to and from .NET Framework objects. The engineering science tin can automatically generate metadata to describe Spider web services in the Web Services Description Language (WSDL) | WCF services were developed for edifice applications to send and receive messing past using many formats and conveyed past using any send protocol. Uncomplicated Object Access Protocol (SOAP) is used by default format.The structure of the messages can exist defined using an XML Schema, and at that place are various options for serializing the messages to and from .Cyberspace Framework objects. WCF can automatically generate metadata to describe applications built using the technology in WSDL, and it too provides a tool for generating clients for those applications from the WSDL. Support for sending messages using not only HTTP, but besides TCP and other network protocols. The ability to switch message protocols with minimal effort. Back up for hosting services on hosts other than a Spider web server. Congenital-in back up for the latest Web services standards (SOAP ane.two and WS-*) and the ability to easily support new ones. Back up 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 every bit XML into .NET Framework objects. Defining the complex data types that an ASP.NET service is to utilize requires the definition of .Internet Framework classes that the XmlSerializer can serialize to and from XML. | The DataContractAttribute signifies that goose egg or more than of a type'southward fields or properties are to exist serialized, while the DataMemberAttribute indicates that a particular field or holding is to be serialized. The DataContractAttribute tin be applied to a class or construction. The DataMemberAttribute tin can be applied to a field or a belongings, and the fields and properties to which the attribute is applied can exist either public or 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 XmlSerializer and the attributes of the Organization.Xml.Serialization namespace are designed to allow you to map .NET Framework types to whatsoever valid type divers in XML Schema, then they provide for very precise control over how a type is represented in XML. | The DataContractSerializer , DataContractAttribute and DataMemberAttribute provide very piffling control over how a type is represented in XML. You can only specify the namespaces and names used to correspond the type and its fields or properties in the XML, and the sequence in which the fields and properties appear in the XML. Everything else well-nigh the construction of the XML used to correspond the .Internet type is adamant by the DataContractSerializer . By not permitting much control over how a type is to be represented in XML, the serialization process becomes highly anticipated for the DataContractSerializer , and, thereby, easier to optimize. |
Lesser functioning compared with WCF DataContractSerializer . | A practical do good of the pattern of the DataContractSerializer is better performance, approximately ten percent better performance. |
The attributes for use with the XmlSerializer do not signal which fields or properties of the blazon are serialized into XML. | DataMemberAttribute for use with the DataContractSerializer shows 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 XmlSerializer tin can merely translate the public members of a .Cyberspace object into XML. | The DataContractSerializer tin can interpret the members of objects into XML regardless of the admission modifiers of those members. |
Instances of collection classes can be serialized into XML only if the classes implement either the IEnumerable or ICollection interface. | The DataContractSerializer is much more probable to exist able to serialize the instances of any pre-existing .NET blazon into XML without having to either modify the definition of the type or develop a wrapper for information technology. |
Classes that implement the IDictionary interface, such as Hashtable , cannot be serialized into XML. | It can translate into XML types like Hashtable that implement the IDictionary interface. |
XmlSerializer does not support versioning. | The DataContractSerializer incorporates some support for versioning. |
XmlSerializer serializes a type by default is semantically identical to the XML. | DataContractSerializer serializes a blazon, provided the namespace for the XML is explicitly defined. |
What is Remainder & RESTful?
Representational State Transfer (Residue) is introduced by Roy Fielding on 2000; it is an architectural fashion of large-scale networked software that takes reward of the technologies and protocols of the Globe Wide Spider web. Remainder illustrate how full-bodied data objects, or resources, can be defined and addressed, stressing the easy commutation 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 Network-based Software Architectures.
REST, an architectural style for building distributed hypermedia driven applications, involves edifice Resources-Oriented Architecture (ROA) by defining resources that implement uniform interfaces using standard HTTP verbs (GET
, Post
, PUT
, and DELETE
), and that can exist located/identified by a Uniform Resource Identifier (URI).
REST is not tied to whatever particular technology or platform – it's just a way to design things to work like the Spider web. People often refer to services that follow this philosophy every bit "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 "Spider web" with HTTP request/response messages. |
It works based on the Remote Procedural Call (RPC) | Information technology is working with HTTP's uniform interface |
Service Reference has to add in the customer applications | No demand to add the service reference in the client applications |
What is the REST Starter Kit?
The WCF Residue Starter Kit is a prepare of .Cyberspace Framework classes and Visual Studio features and templates that enable users to create and access Residue-style Windows Advice Foundation (WCF) services. These services are based on the WCF spider web programming model bachelor in .Internet 3.v SP1. The starter kit also contains the total source code for all features, detailed lawmaking samples, and unit tests.
Creating basic RESTFul Service
Pace 1
Create a new WCF projection using VS2010.
Linguistic communication | Visual C# or Visual Basic |
Target Framework | .NET Framework 4 |
Installed Templates | WCF |
Template | WCF Service Application |
Proper name | RESTFulDemo |
Footstep two
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 a simple member for this entity. For DataContractSerialization
decorate this class and fellow member with DataContract
& DataMember
attributes. Run across the code beneath:
[ DataContract] public grade Person { [DataMember] public string ID; [DataMember] public string Name; [DataMember] public cord Age; }
Person
course and its members decorated with [DataContract]
& [DataMember]
using Organisation.Runtime.Serialization
namespace.
-
[DataContract]
– An entity class which tin can beDataContractSerializable
over the network. -
[Datamember]
– Only busy with[Datamember]
property can exist serializable & too property of the class must be decorated with[DataContract]
Step 4
Create methods in IRESTService
class and interface decorated with [ServiceContract]
& its members busy with [OperationContrat]
using Arrangement.ServiceModel
namespace.
[ ServiceContract] public interface IRestSerivce { [OperationContract] Person CreatePerson(Person createPerson); [OperationContract] List<person> GetAllPerson(); [OperationContract] Person GetAPerson(string id); [OperationContract] Person UpdatePerson(cord id, Person updatePerson); [OperationContract] void DeletePerson(string id); }
-
[ServiceContract]
- A service contract exposes class or interface to the customer applications, which may contain ane or more than[OperationContract]
methods. -
[OperationContract]
- Indicates that a method defines an performance that is function of a service contract in an application, i.due east., only the method decorated with[OperationContract]
is visible for WCF customer awarding and class of this method must exist decorated with[ServiceContract]
.
Pace v
Up to this level, code is similar to that normal WCF services, RESTful services works under HTTP protocol, equally at that place is two important attributes WebGet
& WebInvoke
( System.ServiceModel.Web
namespace) has to include for making this awarding as RESTful service.
WebGet and WebInvoke
WebGet operation is logically receiving the information from a service operation & it tin can be called by the REST programming model. The WebGet
aspect is applied to a service performance in improver to the OperationContract
and assembly the operation with a UriTemplate
as well as the HTTP protocol Get verb.
WebInvoke operation logically raises a service option & it tin can be called by the Remainder programming model. The WebInvoke
attribute is practical to a service performance in addition to the OperationContract
and associates the functioning with a UriTemplate
also as an underlying ship verb that represents an invocation (for example, HTTP POST
, PUT
, or DELETE
). WebInvoke
has a belongings called Method
, it allows specifying different types of HTTP methods (POST
, PUT
or DELETE
), and by default Method
is Mail
.
[ ServiceContract] public interface IRestSerivce { [OperationContract] [WebInvoke(UriTemplate = " ", Method = " POST")] Person CreatePerson(Person createPerson); [OperationContract] [WebGet(UriTemplate = " ")] List<person> GetAllPerson(); [OperationContract] [WebGet(UriTemplate = " {id}")] Person GetAPerson(cord id); [OperationContract] [WebInvoke(UriTemplate = " {id}", Method = " PUT")] Person UpdatePerson(string id, Person updatePerson); [OperationContract] [WebInvoke(UriTemplate = " {id}", Method = " DELETE")] void DeletePerson(cord id); }
Please see the modified code for IRESTService
interface, WebGet
& WebInvoke
attributes decorates for methods available in the IRESTService
interface.
Person CreatePerson(Person createPerson); List<person> GetAllPerson(); Person GetAPerson(cord id); Person UpdatePerson(string id, Person updatePerson); void DeletePerson(string id);
Pace 6
Implement the IRESTService
in the RESTService
form and complete the business requirements. Delight see the sample lawmaking below:
public class RestSerivce : IRestSerivce { List<person> persons = new List<person>(); int personCount = 0; public Person CreatePerson(Person createPerson) { createPerson.ID = (++personCount).ToString(); persons.Add together(createPerson); return createPerson; } public Listing<Person> GetAllPerson() { return persons.ToList(); } public Person GetAPerson(cord id) { return persons.FirstOrDefault(e => e.ID.Equals(id)); } public Person UpdatePerson(string id, Person updatePerson) { Person p = persons.FirstOrDefault(due east => e.ID.Equals(id)); p.Name = updatePerson.Proper name; p.Age = updatePerson.Age; return p; } public void DeletePerson(string id) { persons.RemoveAll(e => east.ID.Equals(id)); } }
Footstep seven
Nosotros have to make this service able to exist run in ASP.Cyberspace compatibility mode, for this AspNetCompatibilityRequirements
attributes have to decorate with the RESTService
class.
[ AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class RESTSerivce : IRestSerivce { }
In the higher up RESTService
class additionally decorated with ServiceBehavior
attribute, it specifies internal behavior of a service operation.
Footstep 8
For using this RESTFul service awarding, this service has to host. So we need to exist done below modification for running the RESTService
.
Modifying the Web.Cogfig File
Remove all the lawmaking within the <system.servicemodel>
tag and insert the code below:
< serviceHostingEnvironment aspNetCompatibilityEnabled =" true" > < /serviceHostingEnvironment > < standardEndpoints > < webHttpEndpoint > < standardEndpoint name =" " 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 go WebHelp for the RESTFul awarding.
Add Global.asax File
We can host RESTFul services using Global.asax file using the below code:
RouteTable.Routes.Add(new ServiceRoute (" RestService", new WebServiceHostFactory(), typeof(RESTSerivce)));
Stride 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 Get
performance.
http://localhost:XXXX/restservice/help - It displays the aid content for RESTFulDemo service.
Still we saw near creating and hosting the RESTFul services, next we have to eat this service, therefore we will see bones application to consume this RESTFulDemo service.
Consuming RESTFul Service
Step 1
Add a new console awarding to RESTFulDemo
solution.
Language | Visual C# or Visual Basic |
Target Framework | .Net Framework iv |
Installed Templates | WCF |
Template | Console Application |
Proper noun | RESTClient |
Stride two
exercise { try { string content; Console.WriteLine(" Enter Method:"); string Method = Console.ReadLine(); Panel.WriteLine(" Enter URI:"); string uri = Console.ReadLine(); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; req.Method = Method.ToUpper(); if ((" Postal service,PUT").Split(' ,').Contains(Method.ToUpper())) { Panel.WriteLine(" Enter XML FilePath:"); string FilePath = Panel.ReadLine(); content = (File.OpenText(@FilePath)).ReadToEnd(); byte[] buffer = Encoding.ASCII.GetBytes(content); req.ContentLength = buffer.Length; req.ContentType = " text/xml"; Stream PostData = req.GetRequestStream(); PostData.Write(buffer, 0, buffer.Length); PostData.Close(); } HttpWebResponse resp = req.GetResponse() equally HttpWebResponse; Encoding enc = Organization.Text.Encoding.GetEncoding(1252); StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc); cord Response = loResponseStream.ReadToEnd(); loResponseStream.Close(); resp.Close(); Console.WriteLine(Response); } grab (Exception ex) { Panel.WriteLine(ex.Bulletin.ToString()); } Console.WriteLine(); Console.WriteLine(" Do you want to continue?"); } while (Console.ReadLine().ToUpper() == " Y");
Footstep iii
Earlier running the RESTFulDemo
application, set multiple startup projects. Please see the below image:
RUN the awarding. It will run the RESTFulDemo service
as well as RESTClient
console awarding.
HTTP Become Operation
Enter Method: | Get |
Enter URI: | http://localhost:XXXX/restservice |
It gives the XML output in the console screen.
HTTP POST Functioning
Enter Method: | Post |
Enter URI: | http://localhost:XXXX/restservice |
Enter XML File Path: | <enter input xml file path> |
This operation creates a new person entity in the service, it tin can be seen in the browser past HTTP Become
performance.
In the higher up screen, call the URI http://localhost:XXXX/restservice/1, URI ends with person ID (i). It calls the service functioning.
[ OperationContract] [WebGet(UriTemplate = " {id}")] Person GetAPerson(string id);
And then it retrieves the person with ID 1.
Please refer to the attached project for detailed code.
Fiddler tool is more useful to test the RESTFul services.
Determination
I hope this article helps yous to empathise basic concept of RESTFul and that the reader is able to code to create & consume RESTFul service. Please let me know your valuable comments.
References
- http://msdn.microsoft.com/en-united states of america/library/aa738737.aspx
- http://msdn.microsoft.com/en-united states/netframework/dd547388
- http://msdn.microsoft.com/en-us/library/dd203052.aspx
- http://msdn.microsoft.com/en-us/library/organisation.servicemodel.web.webinvokeattribute.aspx
- http://msdn.microsoft.com/en-us/library/organisation.servicemodel.web.webgetattribute.aspx
Source: https://www.codeproject.com/Articles/255684/Create-and-Consume-RESTFul-Service-in-NET-Framewor
Posted by: emersonfaccul.blogspot.com
0 Response to "How To Add Ssl To Restful Service"
Post a Comment