RestFul Service based on The. Net framework

Source: Internet
Author: User
Tags http post representational state transfer visual studio 2010 wsdl

About this article

The purpose of this article is to show you how to create a restful service in THE. NET Framework 4.0 and use it.

What is Web Services and what is WCF

The first is the Web Service, a part that allows the client program to request data through the HTTP protocol on a web Page. We can create normal Web services with asp. and let these services be called by the client Program.

The second is web Services, a programming platform that can receive or send data by following the simple Object Access Protocol (SOAP) Approach.

Then there is wcf, which is able to write a programming model based on the service-oriented architecture (SOA) Service. Through it, developers can write out a cross-platform, secure, and reliable Solution.

WCF can provide centralized computing services for a wide variety of customers, and customers can invoke multiple services, while the same service can be called by multiple Users.

Before we create our WCF project, We'd better be able to look at this article: Introduction of Window communication Foundation

The following are the data pairs for webservices and WCF Services:

Web Services WCF Services
WEB services can be used to develop soap-based message sending and receiving applications, which are xml-formatted messages that can be serialized using the tool classes provided by The. net Framework. This technique, which can automatically generate metadata (metadata) to describe web services, is called: the Web services Description Language (WSDL) ( Note: WSDL is an XML language that describes the WebService service and describes how to communicate with a web Service. ) WCF services can be used to develop applications that are based on multiple protocol formats, and SOAP is just its default format. Its message format also uses xml, but there are many ways to serialize the XML Data. It can be automatically generated by WSDL to describe its application metadata, but also can be generated using tools.

For wcf, sending messages is not limited to http, TCP or other network Protocols. and it's easy to switch between these Protocols. In addition to being able to run on the server, it also supports hosting, and it is also very easy to support the latest Web services standards (SOAP 1.2 and ws-*).
In addition to being able to send data in the form of soap, it can be done in other ways.
XmlSerializer DataContractSerializer
When asp. net sends data from the server or receives the data from the client, it uses the XmlSerializer to convert the Data. DataContractSerializer indicates that there are 0 or more attributes or fields that need to be serialized, while DataMemberAttribute indicates that a specified attribute or field needs to be Serialized. DataContractAttribute can be applied to properties or fields with public or private, all attributes or fields marked on datacontractattribute, In wcf, known as data contracts (datacontracts), they will be serialized into XML structures by Datacontractserializer.
The XmlSerializer class and its various features under System.Xml.Serialization can transform various. NET Framework types into XML structures, which provide very good control over Xml. Datacontractserializer,datacontractattribute,datamemberattribute provides a very limited amount of control over xml, so you can only identify through Namespaces. You can use DataContractSerializer to manipulate a variety of data structures except xml, which makes datacontractserializer easier to manipulate without adding too many restrictions.
Compared with datacontractserializer, it has a poor performance. DataContractSerializer performance is better, performance will generally increase about 10%
XmlSerializer does not foresee what fields or attributes should or should not be included in the Xml. With datamemberattribute, the data structure can be very clearly known when the DataContractSerializer is Serialized.
XmlSerializer can only serialize members of the public type. DataContractSerializer does not detect the properties of a type Member.
Only collection types that inherit from IEnumerable or ICollection interfaces can be serialized into Xml. DataContractSerializer can convert any. net type into an XML structure.
Classes that inherit from the IDictionary interface, such as hashtable, are not able to be serialized into Xml. Classes that inherit from the IDictionary interface, such as hashtable, can be serialized into Xml.
XmlSerializer does not support version control DataContractSerializer supports version Control.
XmlSerializer the XML semantic structure of the serialization is basically the Same. When DataContractSerializer is serialized into xml, it is necessary to provide a clear namespace.

What is rest and restful?

Representational state Transfer (REST) was proposed by Roy Fielding in 2000. It is a way to build large-scale network software architectures using world Wide web-related Technologies and Protocols. It is intended to illustrate that data resources can be defined and published, especially in terms of simplicity and extensibility of message Exchange.

As early as 2000, one of the chief authors of the HTTP specification, Roy Fielding, wrote an article entitled "architectural Styles and the Design of network-based software Architectures. " Doctoral dissertation, in the paper, the author Says.

REST, an architectural way to build a distributed hypermedia driver that includes defining resources by leveraging standard HTTP Verbs (,,, and GET POST PUT DELETE ) to build resource-oriented Architecture (ROA) Program. This build can be published to the consumer through the uniform Resource Identifier (URI).

REST is not tied to any technology or PLATFORM. It's just designed to work like a Web. This approach is often defined as "restful services," but in fact WCF services, developed using the rest architecture, can also be called restful services.

WCF Services RESTFul Services
The endpoints need to be created between the respective network Protocols. You can send and receive data via HTTP Web.
Support for remote procedural call (RPC) required Need to define an http-based unified interface
Client needs to add a reference to the service side Clients are not required to add references to the service side

About the case code?

In wcf, rest is actually a series of features and templates for the. NET Framework classes and visual studio, through which users can create and use the REST-mode WCF Service. These services are required by the WCF Web programming model in. NET 3.5 SP1. In the later attachments, all the source code, examples, and unit tests are already included.

Create the underlying restful Service

Step one:

Create a new WCF project with visual Studio 2010:

Step two:

Delete your own IService1.cs and service1.svc files and create the following two files: IRESTService.cs &restservice.cs.

Step three:

Create a person entity class and some simple properties in the IService.cs file, together with the DataContract & DataMember features for easy datacontractserialization serialization:

[datacontract]
Class Person
{
    [DataMember (order=1)]
    String ID;
    [DataMember (order=2)]
    String Name;
    [DataMember (order=3)]
    String age;
    [DataMember (order=4)]
    String Address;

note, Be sure to add order=*, otherwise, when the client adds data to the server, some data fields do not have a Value.

Step Four:

Create a method in the Irestservice interface file that is decorated with servicecontract and operationcontrat:

Using system;using system.collections.generic;using system.linq;using system.text;using System.ServiceModel;using System.servicemodel.web;namespace restfuldaemon{[servicecontract] public Interface Irestserivce {//post Operation [operationcontract] [webinvoke (uritemplate = "", Responseformat = Webmessa geformat.xml, Requestformat = webmessageformat.xml, Method = "POST")] person Crea        Teperson (person createperson); Get operation [operationcontract] [webget (uritemplate = "", Responseformat = webmess        ageformat.xml, Requestformat = webmessageformat.xml)] list<person> Getallperson ();        [operationcontract] [webget (uritemplate = "{id}", Responseformat = webmessageformat.json, Requestformat = WebM        essageformat.json)] person Getaperson (string id); PUT Operation [operationcontract] [webinvoke (uritemplate = "", Responseformat = Webmessageform At. Json, Requestformat = webmessageformat.json, Method = "PUT")] string Updateperson (Per        Son updateperson);  DELETE operation [operationcontract] [webinvoke (uritemplate = "", Responseformat    = webmessageformat.json, Method = "DELETE")] string Deleteperson (string id); }}

code, you can use JSON to organize your data, or you can use XML to organize your data

Step five:
The webget operation is simply an operation that receives data from the server, which can be called by the rest programming model. It will be applied to the method along with the operationcontact, with the UriTemplate property and the get operation in HTTP.
POSTPUTDELETE), and operationcontact at the same time, it indicates that the current method supports different types of HTTP Transports. The default is post Mode.
Here are the specific instructions:
Person Createperson (person createperson);
It is basically inserts operation, so WebInvoke HTTP POST is used
List<person> Getallperson ();
Person Getaperson (string id);
These methods retrieve the information, so WebGet (HTTP Get) is used
Person Updateperson (person updateperson);
This method updates the available information, so WebInvoke HTTP PUT is used
void Deleteperson (string id);
is used
Step six: Implement the Irestservice interface in the Restservice class:
public class Restservice:irestserivce {list<person> persons = new List<person> ();        private static int tCount = 0;            Public person Createperson (person Person) {tcount++;            Person.id = tcount.tostring (); Persons.            ADD (person);        Return person; } public list<person> Getallperson () {return persons.        ToList (); Public person Getaperson (string Id) {return persons. FirstOrDefault (e = E.id.        Equals (id)); The public string Updateperson (person updateperson) {person p = persons. FirstOrDefault (e = E.id.            Equals (updateperson.id));            P.name = updateperson.name+ "[updated]";            P.age = updateperson.age+ "[updated]";            p.address = updateperson.address+ "[updated]";        return "Updated success"; public string Deleteperson (string id) {persons. RemoveAll (e =&GT E.id.            Equals (id));        Return "success"; }    }

Step seven: in order for this service to work in asp. net compatibility mode, We need to use the Aspnetcompatibilityrequirements feature to decorate the Restservice class:
[aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode.allowed)]    [servicebehavior (instancecontextmode = instancecontextmode.single)]    public class Restservice:irestserivce    {       //code here    }

So the current code is as Follows:
Using system.collections.generic;using system.linq;using system.servicemodel.activation;using System.ServiceModel; Using system;namespace restfuldaemon{[aspnetcompatibilityrequirements (requirementsmode =    aspnetcompatibilityrequirementsmode.allowed)] [servicebehavior (instancecontextmode = InstanceContextMode.Single)]        public class Restservice:irestserivce {list<person> persons = new List<person> ();        private static int tCount = 0;            Public person Createperson (person Person) {tcount++;            Person.id = tcount.tostring (); Persons.            ADD (person);        Return person; } public list<person> Getallperson () {return persons.        ToList (); Public person Getaperson (string Id) {return persons. FirstOrDefault (e = E.id.        Equals (id)); The public string Updateperson (person updateperson) {person p = persons. FirstOrDefault (e => E.id.            Equals (updateperson.id));            P.name = updateperson.name+ "[updated]";            P.age = updateperson.age+ "[updated]";            p.address = updateperson.address+ "[updated]";        return "Updated success"; public string Deleteperson (string id) {persons. RemoveAll (e = E.id.            Equals (id));        Return "success"; }    }}

In the above class, the class is preceded by the ServiceBehavior feature, which is mainly used to illustrate that only one instance of this class exists on this server.
Step eight: If you want to use this restful service app, you must be hosted. so we have to make the following changes to get Restservice to Run. in the Web. config file, remove < System.servicemodel> all the code below, and add the following new code:
<system.servicemodel> 
    <aspnetcompatibilityenabled= "true">  
    </servicehostingenvironment> 
    <standardendpoints> 
      <webhttpendpoint> 
        <namehelpenabledautomaticformatselectionenabled= "true"></  Standardendpoint>      
      </webhttpendpoint> 
    </standardendpoints> 
  </system.servicemodel> 

Where the,<servicehostingenvironment> tag is used to make the current app will run in asp. net compatibility mode.

<standardEndpoints>Tags are used to get webhelp for restful apps.

then, in the Global.asax file, we need to add the following code to the Application_Start event:

ROUTETABLE.ROUTES.ADD (new Serviceroute (typeof (restserivce)));   
Step nine: Run the application: http://localhost:****/restservice we can see the following page: when running http://localhost:****/restservice/help, We can see the following page: how to use a restful service?

Client-side programming

Here I first post the client code:

View Code

The following is a client program written using wpf, which displays the results when you click on the "create user" button:

When you click on "get all users", the ID number of all users will be given: the result when the "get a user" button is clicked (2nd User information is obtained): results when the "update a user" button is clicked (number 3rd user information is updated):

When you click on the "delete a user" button when the display results (4th number of users were deleted):

The client side displays the following results:

SOURCE download

Click here to get source code

Reference Resources: Design a RESTful service with. NET Framework 4.0How to consume a RESTful service from The. Net Framework 4.0Special Note: This article is reproduced from http://www.cnblogs.com/scy251147/p/3382436.html, but the examples in this paper can fully demonstrate the CRUD process on the client Side.

RestFul Service based on The. Net framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.