Understanding of the REST architecture and Jquery + JSON + RESTful WCF (with source code)

Source: Internet
Author: User
Tags introductions representational state transfer

 

I recently read some introductions about the REST architecture style and summarized my understanding of REST. This article is the most personal achievement for reference by children's shoes interested in REST development. If you have any mistakes, please kindly advise.

After reading REST for many days, I wrote some DEMO programs to deepen my understanding of it. In the evening, I suddenly found a plug-in name (WCF REST Starter Kit Preview 2.msi,: http://aspnet.codeplex.com/releases/view/24644) was released by Microsoft. As my first WCF article about REST style, this article begins with the most basic use of this plug-in.

This article consists of two parts:

  1. Brief Introduction to REST

2. JQ + JSON + WCF (REST) and C # client call the DEMO of RESTful WCF Service.

3. rest wcf help Page

*Brief Introduction to REST

First, we will introduce what is REST. REST is called Representational State Transfer. It is neither a framework nor a specification, but a network application design style and development method that can reduce development complexity and improve system scalability. The REST design principles are as follows:

1. Everything on the network is abstracted as a Resource ). Such as images, music, and services

2. All resources on the network have a Unique Identifier (Unique Identity), that is, URI (UniformResource Identifier)

3. Resource Operations are accessed through unified universal interface specifications. For example, use the HTTP standard verb GET, POSt, DELETE, and PUT for access.

4. Access to a resource does not change its unique identifier, that is, the URI remains unchanged.

5. All operations are stateless.

Since REST is based on the HTTP protocol. Therefore, the third point in the above principles is easy to understand. Similarly, as long as the client supports resource access through the HTTP protocol, the RESTful Service will handle the issue accordingly. Of course, because of its inherent characteristics, cross-platform is not a problem.

Of course, HTTP has a total of eight verbs to indicate different operations on the resources requested by the client, respectively:

  • OPTIONS
    Returns the HTTP Request Method supported by the server for a specific resource. You can also use the '*' request sent to the Web server to test the server's functionality.
  • HEAD
    Request the server for the same response as the GET request, but the response body will not be returned. This method can obtain metadata contained in the Response Message Header without transmitting the entire response content.
  • GET
    Send a request to a specific resource. Note: The GET method should not be used in operations that produce "Side effects", for example, in Web Application. One of the reasons is that GET may be randomly accessed by web spider.
  • POST
    Submits data to a specified resource for processing (for example, submitting a form or uploading a file ). Data is contained in the request body. POST requests may result in creation of new resources and/or modification of existing resources.
  • PUT
    Upload the latest content to the specified resource location.
  • DELETE
    Request server DeletionRequest-URIResource.
  • TRACE
    The request received by the echo server is mainly used for testing or diagnosis.
  • CONNECT
    The HTTP/1.1 protocol is reserved for proxy servers that can change connections to pipelines.

Of course, in RESTful Service, you can use GET, POST, PUT, and DELETE to operate resources.

* DEMO

First, we will introduce how to change the development environment (install and download the wcf rest Starter Kit Preview 2 ):

Environment: VS 2008 + wcf rest Starter Kit Preview 2.

1. Create a project first, such:

2. The structure after the project is created is as follows:

      

    

The Service is defined as follows:

Public class Service: SingletonServiceBase <SampleItem>, ISingletonService <SampleItem>

{

/**/

}

If you have experience with WCF, you can think of ISingletonService <SampleItem> as a service contract. Service Code and

The codes of SingletonServiceBase <SampleItem> and ISingletonService <SampleItem> in generic classes are automatically generated by the system.

The source code of the class is not provided. Let's just talk about how ISingletonService <SampleItem> specifies the public interface specifications returned by the resource.

[OperationContract]
[WebHelp (Comment = "Returns the item in JSON format.")]
[WebGet (UriTemplate = "? Format = json ", ResponseFormat = WebMessageFormat. Json)]
TItem GetItemInJson ();
[OperationContract]
[WebHelp (Comment = "Returns the item in XML format.")]
[WebGet (UriTemplate = "")]
TItem GetItemInXml ();

[WebHelp (Comment = "Initializes the item based on the incoming JSON.")]
[OperationContract]
[WebInvoke (Method = "POST", UriTemplate = "? Format = json ", ResponseFormat = WebMessageFormat. Json)]
TItem AddItemInJson (TItem initialValue );

The public interfaces of resources are formulated using the methods and UriTemplate templates in WebGetAttribute, WebInvokeAttribute. Method defines the actions to access resources, such as POST and GET (or others. Here, only the different actions in 2 are listed for illustration ). UriTemplate specifies the resource access URI. In rest wcf, The UriTemplate is essential in the definition of the service contract, and the Method is specified. The default action in WebGet is GET. Of course, if you want to define it in WebInvoke, but since WebGet already exists, why do you do it multiple times .?

1. the JQ call code is as follows:

View sourceprint?
$.ajax({
   
         type: "GET",
   
         url: "Service.svc/?format=json",
   
         dataType: "json",
   
         contentType: "application/json; charset=utf-8",
   
         success: function(json) { alert(json.Value) },
   
         error: function(error) {
   
         alert("Call error" + error.responseText);
   
         }
 });

 

Note: The URL path in AJAx call. As the JSON format is used here, the server is required to return the JSON data format. If the path is not written as "", an exception will be thrown during the call, for example:

Path: Service. cs and Service. cs? Format = JSON is defined in ISingletonService <T> (the preceding two methods are used to access the two resources in the preceding public interface specification instance code for the specified resource ).

The correct access result is as follows:

Note: You may notice that,When obtaining JSON data, you do not want to use JSON. d to obtain data after accessing the service through SOAP.JSON. Value is used here. In this example, the generic class uses SampleItem, so it is obtained through its attribute Value. Different object types should be analyzed in detail.

2. C # call:

2.1. WebClient

Using (WebClient client = new WebClient ())
{
String str = client. DownloadString ("http: // localhost: 3103/Service. svc /");

Response. Write (str );
}

2.2 HttpWebRequest and HttpWebResponse.

HttpWebRequest webRequest = WebRequest. Create ("http: // localhost: 3103/Service. svc /? Format = json ") as HttpWebRequest;
HttpWebResponse webResponse = webRequest. GetResponse () as HttpWebResponse;
Using (StreamReader reader = new StreamReader (webResponse. GetResponseStream ()))
{
Response. Write (reader. ReadToEnd ());
}

The result is as follows:

In the preceding two access methods, if you change the path to http: // localhost: 3103/Service. svc /? Format = json, The JSON object is output as a string. If you are interested, try it.

3. rest wcf help Page:

In the address bar, enter http: // localhost: 3103/Service. svc/to display the resource call result. Add help (http: // localhost: 3103/Service. svc/) after the address to view the help Page. For example:

The above access methods, methods, and other information have already been clearly displayed, so you do not need to explain it more. Of course, this help page is available in REST WCF4.0

More friendly and clear expression form. I will give you another opportunity later.

 

Summary:1. Define the interface access Method (specified through UriTemplate) in the contract, and specify the Method

2. How does JQ call the communication between the JSON data format and the rest wcf Service.

3. view the help page of the service

Another: 1. This article is intended for beginners. Let's have a rough understanding of it. There will be some in-depth introductions in the future

2. In my DEMO, [DataContract] and [DataMember] are not specified for the data contract SampleItem. I added them manually.

3. http: // localhost: 3103/Service. svc/You can only view the final call result in the browser, but http: // localhost: 3103/Service. svc /? If format = json, the system prompts you to download the file. After the file is downloaded, the content in it is the same as that in C # By simulating Http requests.

Source code: http://www.bkjia.com/uploadfile/2011/1103/20111103115010107.rar

Refer:

Http://www.bkjia.com/kf/201111/110017.html

Http://baike.baidu.com/view/1077487.htm

<Script> </script>

 

 


Author: tyb1222

Related Article

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.