Jquery + JSON consume REST WCF4.0 service (with source code)

Source: Internet
Author: User
Tags api manual

As a HTTP-based WCF Service, as long as the client can simulate HTTP requests, it can become a service consumer. I have written about Jquery + JSON + WebService before. I think the REST is based on the HTTP protocol and AJAX operations should be the same. But there are actually some differences. As there are few chat resources on the Internet, record your personal experience. Hope to help you!
This article describes how to use AJAX to consume REST services in ASP. NET.
When using the JQUERY framework to simulate AJAX requests, there are two main types of operations: GET and POST. This section also describes the two common methods. (Type (String): (default: "GET") Request Method ("POST" or "GET"). The default value is "GET ". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but are only supported by some browsers. From: Jquery 1.4 API Manual ).

  • The main operations involved in this article are as follows:
  • 1. GET request
  • 2. POST request, simple data type
  • 3. POST requests, complex data types

When Jq + JSON consumes the REST WCF4.0 service, the format of the data returned to the client and the format of the data transmitted from the client to the server are specified through the ResponseFormat and RequestFormat enumeration types. The following code is used.

Server implementation code:

public class AjaxService{    [WebGet(UriTemplate = "/{id}"    ,ResponseFormat =WebMessageFormat.Json    , RequestFormat = WebMessageFormat.Json)]    public Person GetPerson(string id)    {    return new Person    {      Id = int.Parse(id),       Age = 27,       Name = "zhansan",       Phone = "01082667896"    };  }  [WebInvoke(UriTemplate = "/Post"  , BodyStyle = WebMessageBodyStyle.WrappedRequest  , ResponseFormat = WebMessageFormat.Json  , RequestFormat = WebMessageFormat.Json)]  public string UpdatePerson(Person person)  {    return person.Id + person.Name + person.Age + person.Phone;  }  [WebInvoke(UriTemplate = "/Rest/Post"  , BodyStyle = WebMessageBodyStyle.WrappedRequest  , ResponseFormat = WebMessageFormat.Json  , RequestFormat = WebMessageFormat.Json)]  public string Update(string message)  {    return string.Concat("hello", message);  }}

  

Client implementation code
1. GET request.

$. Ajax ({type: "get", url: "AjaxService/36", contentType: "application/json; charset = UTF-8", success: function (json) {alert (json. name)}, error: function (error) {alert ("call error" + error. responseText );}});

The effect is as follows:

2. POST request, simple data type.

Var jsonMsg = {'message': 'hangsan'}; var message = JSON2.stringify (jsonMsg) $. ajax ({type: "POST", url: "AjaxService/Rest/Post", contentType: "application/json", data: message, dataType: "text", processData: false, success: function (json) {alert (json)}, error: function (error) {alert ("call error" + error. responseText );}});

The running result is as follows:

3. POST requests, complex data types
The complex data types of POST are the same as those of simple types. Construct a JSON data object on the Web page and convert it to a JSON string format.
The Code is as follows:

Var jsonData = {'person ': {'id': '36', 'name': 'hangsan', 'age': '27', 'phone ': '200' }}; var message = JSON2.stringify (jsonData) $. ajax ({type: "POST", url: "AjaxService/Post", contentType: "application/json; charset = UTF-8", data: message, dataType: "json ", success: function (json) {alert (json)}, error: function (error) {alert ("call error" + error. responseText );}});

The running result is as follows:

As in WebService: Data in JSON string format uploaded by the client is included in the corresponding fields of the complex data type on the server.
In this way, the interaction with rest wcf is completed through JQ + JSON. However, when using the POST operation, you must specify the WebMessageBodyStyle during the interaction between the client and the server, regardless of the format. Purpose: Specify whether to encapsulate parameters and return values. That is, during the interaction between the client and the server, the parameters uploaded to the server and the return values sent from the server to the client need to be packaged. This is very important, otherwise there will be exceptions when calling the consumption service.
WebMessageBodyStyle is defined as follows:

public enum WebMessageBodyStyle{  Bare,  Wrapped,  WrappedRequest,  WrappedResponse}

MSDN provides the following description:

  • Bare does not encapsulate requests and responses.
  • Wrapped wraps requests and responses.
  • WrappedRequest wraps the request, but does not wrap the response.
  • WrappedResponse wraps the response, but does not wrap the request.

Summary of WebService call similarities and differences:

  • 1. The call method is the same.
  • 2. The data format sent from the client to the server is slightly different. In WebService, you can perform the following operations:data: "{'name':'zhangsan'}"To send requests to the server, but this string format is not supported in RESTful.
  • 3. Obtain the WebService call result through. d, that is, json. d. In RESTful Service, you can directly obtain json.
  • 4. You do not need to specify the format of the client request and server for WebService. In RESTful Service, you must specify

This process is not complex, and it is easy for people with such development experience. However, for those who first came into contact with REST development, they still need to take a long time to complete.

Refer:

Http://www.west-wind.com/weblog/posts/2008/Apr/21/jQuery-AJAX-calls-to-a-WCF-REST-Service

Jquery1.4 API Manual

MSDN

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.