The following figure describes the whole model:
In order for AJAX pages to call remote services, services must meet several requirements, the most critical of which is related to the location of endpoints and underlying platforms. AJAX-enabled services must be in the domain of the caller. This means that the service must be an XML Web service (. Asmx endpoint), which must reside as an application in the IIS application of the same Web server.
Generally speaking, for AJAX application services, there are three ways to define server-tier services:
1. XML Web service with asmx endpoint.
2. WCF service with svc endpoint.
3. Page methods with aspx endpoints, which are defined in the same page as keynote pages.
The word "service" is often misused. In AJAX, service refers to the code belonging to the application (located in the domain of the application), which is used to expose the corresponding functions to the client. Fundamentally speaking, the services used by AJAX applications generally do not communicate through Simple Object Access Protocol (SOAP), but use JSON, and do not need to be autonomous services in service-oriented architecture (SOA). They are bound to their own platforms and domains. Therefore, the services here cannot be called WS-*Web services and SOA services.
Rest service
The services of AJAX applications revolve around data and resources exposed to Web clients. Both of them can be obtained through HTTP, which requires clients to access data and command operations through URL (which can also have HTTP headers). The interaction between the client and the service is completed by operations such as GET, POST, PUT and DELETE. In other words, the URL is used to describe the resource to be obtained, and the HTTP action is used to describe the operation performed on the resource. The data exchanged in this kind of interaction is expressed in a simple format, or even in a joint format (such as RSS and ATOM).
A service with these characteristics is representative state transition (REST).
Serialization of data
AJAX calls contain data passed as parameters to the called service method and data returned as output. How are these data serialized?
The serialization format that both sides can understand is JavaScript Object Representation (JSON). JSON is a text-based format, which is specially used to transfer the state of objects between different levels. JavaScript supports JSON, and JSON-compatible strings can be converted into JavaScript objects through JavaScript's eval function. However, if a JavaScript string represents the state of a custom object, developers should ensure that there is a definition of the corresponding class.
The AJAX network stack is responsible for creating JSON strings for each remotely passed object. On the server side, data is received and passed through a special formatter class. NET reflection to fill the matching managed class. On return. NET managed classes will be serialized as JSON strings and sent to the client. The script manager will ensure that classes that reference these JSON strings (Web service proxy classes) exist on the client.
The following is an example of JSON format describing the state of an object:
{"ID":"ALFKI "," Company":"Alfred Futterkiste"}
This string indicates that the object has two attributes: ID and Company, and it stores the serialized value as a string. If an attribute is given a value of a non-basic type (such as a custom object), the value will be recursively serialized as JSON. [
JSON and XML
Compared with XML, JSON is more refined and more suitable for JavaScript language.
Application-specific Web services
By default, Web services send and receive SOAP packets (not JSON packets), and their contracts are exposed through Web Services Description Language (WSDL) documents. How does an XML Web service work in the context of an AJAX application?
You can modify the HTTP handler that receives asmx requests through the web.config file of an AJAX application and redirect these calls to an HTTP handler that can understand JSON streams. This means that XML Web service can be a dual service, that is, it can accept and process SOAP requests, and it can also target JSON requests. At the configuration layer, we can disable SOAP support and hide the WSDL files used to expose service functions to the outside world.
If you want to use a JSON-enabled Web service, you need to delete XML, because we don't deal with SOAP and XML when calling the Web service. Web services of AJAX applications do not use SOAP messages.
Definition of remote programming interface
Contracts are used to define what server-side endpoints expose to callers. If you want to implement it as a Web service, it is not strictly required to have an actual contract. But if WCF serves 3.5, then the contract must exist. In short, a public API designed in the form of an interface will make the code cleaner. After creating the class that implements the interface, the work of the server API interface is over. In this way, we can publish this remote API and let the AJAX runtime manage the calls from the client.
For Web services, we define the contract through a pure interface, so that the interface contains methods and properties related to the server API. Here is a simple service:
Use the system; Public interface ITimeService{
DateTime GetTime();
String GetTimeFormat (string format); }
These two methods constitute a server API that can be called on the client.
Implement the agreed interface.
Web services are usually accessed through. NET class to achieve:
Use the system. Network service; Public class time service: WebService, ITimeService{
}
Note that it is not necessary to derive from the base class WebService, and it is mainly used to directly access some common objects (such as applications and sessions). If you don't need to access these internal objects directly, you can create a WebService without deriving from the Web service class. In this case, we can use the internal object indirectly through the HttpContext object.
Release of the agreement
Essentially, publishing a given server contract is to generate a JavaScript proxy class that can be called by scripts embedded in the page. If the server API is implemented through Web services, we need to register the Web services with the script manager of AJAX pages. In addition, we need to add a special asmx request HTTP handler to the web.config file.
Remote invocation of Web services
Web services provide a host environment for server-side code called in response to client operations. Web methods in services point to application-specific code.
Creation of AJAX Web service
Web services customized for AJAX applications are smaller than other Web services. There are two differences between AJAX Web services and traditional XML Web services.
First of all, if AJAX Web services are used, then in order to meet the needs of specific applications, we should design the contract of AJAX Web services instead of configuring the behavior of public services. The target application is the host of the Web service. Secondly, we must use a new attribute to declare the class of this Web service, which is not allowed in traditional XML Web services.
The end result is that AJAX Web services may have two sets of public interfaces: one is based on JSON interface and used by host AJAX applications; The other is an interface based on SOAP, which is open to clients and any platform can access the URL of the service.
ScriptService property
To create AJAX Web services, the first step is to build a standard Web service project and then import it into the system. Web.Script.Services namespace:
Use the system. Web.Script.Services namespace Core35. Web service {
[web service (namespace = "
[web service binding(ConformsTo = WsiProfiles。 BasicProfile 1_ 1)]
[Script service]
Public class TimeService: System. Web.Services.WebService,ITimeService
{
}}
ScriptService feature is the key to distinguish XML Web service from AJAX Web service. This feature indicates that the service is designed to accept calls from JavaScript-based client proxies.
Block SOAP clients
Once you create an AJAX Web service, you can publish it as an ASMX resource. By default, it has a public URL that AJAX clients can call and SOAP clients and tools can find and use. However, we can disable SOAP clients and tools. To do this, simply add the following settings to the web.config file:
network service
protocol
Clear/
/protocol /web service
This simple setting can disable all protocols defined by the Web service (including SOAP), so that the service can only respond to JSON requests.
Please note that if you add these settings, you will not be able to call the Web service through the browser's address bar for simple testing. Similarly, we can't add? WSDL suffix to call wsdl.
Definition of Web service method
Client pages can call public methods with Webmethod characteristics in web service classes. By default, these methods are called through HTTP action POST, and their values are returned as JSON objects. We can change the default settings of individual methods through the optional feature ScriptMethod.
The ScriptMethod function has three attributes, as shown in the following table:
Because of the security and performance issues involved, the following code carefully uses the ScriptMethod function, but does not modify the default settings:
[web method][script method] public date and time GetTime(){
}
The WebMethod function is required, while the ScriptMethod function is optional.
Registration of AJAX Web services
In order to call a Web service on the client, we only need the management function of XMLHttpRequest, the URL of the target Web service and the JSON stream. For convenience, all functions are wrapped in JavaScript proxy classes mapped to remote programming interfaces. The proxy class is automatically generated by AJAX framework and injected into the client.
In order for the built-in engine to generate the required JavaScript proxy and auxiliary classes, we should register the AJAX Web service with the script manager control in the page that needs it:
ASP:script manager ID = " script manager 1 " runat = " server "
service
ASP:service reference Path = " ~/web services/time service . asmx "/
/Services/asp:ScriptManager
For each Web service to be bound to the page, we add a ServiceReference tag and set the Path property to the URL of the corresponding asmx resource. For each service reference, an extra script block is automatically generated on the client. The URL of the script points to a system HTTP handler, and the following URL is called internally:
~/web services/time service . asmx/js
The /js suffix appended to the Web service URL instructs the AJAX runtime to generate JavaScript proxy classes for the specified Web service. If the page is in a debugging template, the suffix will be changed to /jsdebug.
By default, JavaScript agents connect to pages through script tags, which need to be downloaded separately. By setting the InlineScript property of the ServiceReference object to true, we can also merge any required scripts into the current page. If browser caching is enabled and multiple pages use the same service reference, the default value of false is more appropriate. In this case, no matter how many pages need this proxy class, you only need to execute the request once. Setting the InlineScript property to true will reduce the number of network requests, but it will occupy a certain bandwidth.
If you register AJAX Web services programmatically, we will use code similar to the following:
service reference service = new service reference(); Service. path = " ~/web services/time service . asmx "; ScriptManager 1。 Services.Add (service);
Either way, in order to call the Web service, we only need to initiate the call through the JavaScript proxy class.
Hosting AJAX Web services with applications.
To enable Web service invocation in AJAX applications, we need to add the following to the web.config file to register a special asmx request HTTP handler:
In the completed callback, we first reset the user interface, and then do other operations:
Function methodCompletedWithFeedback (result, context, method name) {
$get ("feedback"). innerHTML =
}
Note that when an error occurs, we should also clear the user interface.
Timeout processing
If a client call to the asmx Web service is initiated, it is a direct call to asmx. For this request, there is only a synchronization handler in the runtime. In other words, no matter how the client detects whether the current call is in progress, the thread will be completely blocked until the AJAX method is executed. To do this, we can set a timeout:
Core 35. web services . mysampleservice . set _ time out(3000);
The timeout attribute is global and acts on all methods of the proxy class.
If the request times out, we will not receive the response from the server, and the client can only cancel the execution unilaterally.