Use the Ajax extensions client to call Web Services

Source: Internet
Author: User
Very ASP. NET
Use the Ajax extensions client to call Web Services

Fritz onion
More...
Print
Email
Add to favorites
Rating
RSS (very ASP. NET)
Add RSS to any
Related information
Live Spaces
Digg this
Blogthis!
Slashdot
Del. icio. us
Technorati
Please e the code.

Download the code.

Get the sample code for this article.

DirectoryUse ajax to call Web Services

New: getting e the sample code online!

-Or-

Code download location:Extremeaspnet2007_01.exe (160kb)

Working Principle
Serialization
Summary

Basically, ASP. NET is a server-side technology from beginning to end. Of course, Asp. net will generate client JavaScript, especially in verification controls and in the new Web component infrastructure, but it usually simply converts client properties to client behavior. As a developer, you do not have to consider interacting with the client before receiving the next POST request. For developers who need to use the client JavaScript and DHTML to build more interactive pages, they need to write their own code with some help provided by the ASP. NET 2.0 script callback function. This situation was completely changed last year.

Microsoft released a new ASP at the Microsoft Professional Development Conference in September 2005. net plug-in (Code: "Atlas"), mainly to make full use of client JavaScript, DHTML and XMLHttpRequest objects. The purpose is to help developers create more interactive web applications that support Ajax. This framework is renamed as MicrosoftAjax library and ASP. NET 2.0 Ajax extensions, which provides many outstanding functions, including client data binding, DHTML animation and behavior, and comprehensive interception of client post callback using updatepanel. Many of these functions depend on the ability to asynchronously retrieve data from the server through client JavaScript calls for analysis and interaction. The topic of this month's column is this new very useful capability, that is, the ability to call server-side web services through client JavaScript on pages that support ASP. NET 2.0 Ajax extensions.

Use ajax to call Web Services

If you have used a Web Service in Microsoft. NET Framework, whether using the wsel.exe utility to create a proxy or using Visual StudioYou will get used to using the. Net type to call Web Services. In fact, calling a web service method through a. Net proxy is very similar to calling a method in other classes. The agent prepares XML based on the parameters you pass and converts the XML response it receives to the. NET type specified by the proxy method. Developers can easily use. NET Framework to use web service endpoints, which also makes service-oriented applications feasible.

ASP. NET 2.0 Ajax extensions enables the client JavaScript running in the browser to achieve seamless and identical agent generation experience with Web Services. You can compile a. asmx file hosted on your server and call the method on the service through a client JavaScript class. For example, figure 1 shows a simple. asmx service that implements a simulated stock quotation search (using random data ).

In addition to the standard. asmx web service attributes, this service also adds the scriptservice attribute so that it can also be applied to JavaScript clients. If this. the asmx file is deployed in support of ASP. net Ajax web application, you can. add servicereference to the scriptmanager control in the aspx file, and call the service method from JavaScript (when you use ASP. when a website template of net Ajax is created in Visual Studio, this control is automatically added to your default. in the ASPX page ):

<asp:ScriptManager ID="_scriptManager" runat="server">            <Services>            <asp:ServiceReference Path="StockQuoteService.asmx" />            </Services>            </asp:ScriptManager>            

 

Now you can use the msdnmagazine. stockquoteservice class to call any method of the service through any client JavaScript routine. Because the basic mechanism of calling is asynchronous in nature, there is no synchronous method available. Each proxy method carries an additional parameter (except the standard input parameter), which references another client JavaScript function that is asynchronously called when the method is complete. The example Page shown in Figure 2 uses client JavaScript to display the result of calling the stock quote web service in the tag (SPAN) on the page.

If a problem occurs in the Web service call of the client, you must let the client know about this situation. It is generally wise to call another method for transmission in case of an error, abort, or timeout. For example, you can change the onlookup method shown above as follows and add an onerror method to display all problems:

function OnLookup()            {            var stb = document.getElementById("_symbolTextBox");            MsdnMagazine.StockQuoteService.GetStockQuote(            stb.value, OnLookupComplete, OnError);            }            function OnError(result)            {            alert("Error: " + result.get_message());            }            

 

In this way, if the web service call fails, you will notify the client through the alarm box. You can also add the usercontext parameter to any web service call sent from the client. This parameter is an arbitrary string passed in as the final parameter of the web method, it will be spread as an additional parameter to the methods of success and failure. In this case, it makes sense to pass the actual symbol of the requested stock as usercontext, so that you can display it in the onlookupcomplete method:

function OnLookup()            {            var stb = document.getElementById("_symbolTextBox");            MsdnMagazine.StockQuoteService.GetStockQuote(            stb.value, OnLookupComplete, OnError, stb.value);            }            function OnLookupComplete(result, userContext)            {            // userContext contains symbol passed into method            var res = document.getElementById("_resultLabel");            res.innerHTML = userContext + " : <b>" + result + "</b>";            }            

 

If you find that you want to make multiple different calls to a web service, and you repeatedly use the same error and/or completion method for each call, you can also set global default failure and successful callback methods. This avoids specifying a pair of callback methods for each call. You can also select different methods to ignore global definitions. The following is an example of the onlookup method, where the global (rather than for a single call) default Success and Failure callback methods are set.

// Set default callbacks for stock quote service            MsdnMagazine.StockQuoteService.set_defaultSucceededCallback(            OnLookupComplete);            MsdnMagazine.StockQuoteService.set_defaultFailedCallback(            OnError);            function OnLookup()            {            MsdnMagazine.StockQuoteService.GetStockQuote(stb.value);            }            

 

Another interesting way to build a complete. asmx file for your web service method is to embed the Web service method directly in the page class. If it doesn't make sense to build a complete Web service endpoint for the method you want to call, you can publish a web method that can be called using client JavaScript on your page, the method is to add a server Method to the page (add it directly on the page or add it as a code hidden) and annotate it with the webmethod attribute. Then you can call the client object pagemethods. The example in Figure 3 shows the re-compiled stock quote service example, which is completely included in a page rather than separated into various web services.

Remember that these client proxies can only be generated by ASP. NET. asmx endpoints, Windows Communication Foundation. SVC endpoints, or webmethods directly embedded in the page, and are not a common mechanism for calling any web services. In fact, there are general restrictions on basic XMLHttpRequest objects, and the request scope is limited to loading the page domain (for security reasons). Therefore, this method cannot be used to call any web service, whether or not the client proxy supports this operation. If you find that you need to call the external web service, it is best to call the external web service. net proxy class (generated using wsdl.exe or "add web reference" in Visual Studio. asmx endpoint.

Working Principle

You can use the standard. asmx web service and access it via client Javascript in the browser without making any changes. At first glance, it seems incredible. The secret is that you have registered a new. asmx HTTP handler and added it to the configuration file of every website that supports ASP. NET Ajax:

 

If a standard web service request is made to A. asmx endpoint, the newly registered handler calls the standard Web Service Processing Program (system. Web. Services. Protocols. webservicehandlerfactory ). However, if the request contains a suffix/Js in the URL or a query string containing the Mn = variable (such? Mn = getstockquote), the handler returns a javascript block, creates a client proxy for the Web service (with/JS), or calls the corresponding method defined in the derived class of WebService, and package the response in a JavaScript Object Notation (JSON) encoded string (? Mn = ).

When the page contains. when the client reference of the asmx Service (using the servicereference element in the scriptmanager control), it injects the suffix/JS reference. the script element of the asmx file to create a proxy on the client. For example, the following script elements are displayed on the stock quotation page I built above:

<script src="StockQuoteService.asmx/js"            type="text/javascript"></script>            

 

Of course, this is based on adding a script reference to the Microsoft Ajax library. The Ajax library contains the client functions required for interaction with this proxy. If you try to navigate to this endpoint by yourself, you will see the following JavaScript (partial ):

Type.registerNamespace('MsdnMagazine');            MsdnMagazine.StockQuoteService=function() {            this._timeout = 0;            this._userContext = null;            this._succeeded = null;            this._failed = null;            }            MsdnMagazine.StockQuoteService.prototype={            GetStockQuote:Sys.Net._WebMethod._createProxyMethod(this,            "GetStockQuote",            "MsdnMagazine.StockQuoteService.GetStockQuote",            "symbol"), ...            }            

 

This JavaScript uses the features of the Microsoft Ajax Library (such as the namespace and webmethod class) contained in each page containing the scriptmanager control ). The proxy method created in this JavaScript code is initialized, and the query string in this example is used? Mn = getstockquote calls the. asmx endpoint, so whenever you call msdnmagazine. stockquoteservice. getstockquote from the client, it will become an asynchronous Web request to the same. asmx endpoint. The combination of client proxy generation and server support for Web service calls sent by JavaScript means that you can include client calls to your. asmx web service in an intuitive way.

Serialization

The default serialization of Ajax-based Web Services is JSON. If you notice a series of page operations shown in the previous section, you will find that the main part of the web service request and response is similar:

Request: {"symbol":"ABC"}            Response: 51            

 

This is certainly not your call. the standard XML format used to be seen in asmx web services, because. the asmx endpoint has been serialized to XML during construction, so ASP. NET 2.0 Ajax extensions adds a JSON serialization program. There are actually two serialization programs: one implemented in Javascript for the client and one implemented in. net for the server, especially when the Ajax client calls the. asmx endpoint. The server-side serialization program can be used by Microsoft. Web. Script. serialization. javascriptserializer, and the client-side serialization program can be used by sys. serialization. javascriptserializer. One of the main advantages of using JSON as an XML-based serialization format is that you can simply obtain the value of a JSON string to deserialize objects in Javascript. The deserialization method of the client serialization program class will eventually become very short (with the error check removed ):

Sys.Serialization.JavaScriptSerializer.deserialize=            function(){eval('('+data+')');}            

 

On the other hand, the serialization method of javascriptserializer is more complicated. Another advantage of using JSON is its simplified representation compared with the corresponding XML.

Similar to standard Web services that use xmlserializer to serialize types to XML, you can use almost any. Net Type and use javascriptserializer to serialize it to JSON. If you want to try it yourself, you only need to call the serialize method of the javascriptserializer class. Figure 4 shows an example console application that serializes complex person types, as shown in Figure 5. (This program must contain Assembly references to Microsoft. Web. Extensions. dll. This dll is installed with ASP. NET Ajax extensions in the Global Assembly Cache (GAC .)

The output of the console application will be a person class in JSON format, or:

{"Married":true,"Age":33,"FirstName":"Bob","LastName":"Smith"}            

 

Just like xmlserializer, javascriptserializer serializes only one type of public accessible data, and does not support parsing of circular references. However, any type that can be serialized by the standard. asmx web service can also work properly with this serialization Program (including dataset, of course ). With this in mind, you can build more complex web services because it handles complex types as easily as any soap-based Web Service defined in the. asmx file.

The example in Figure 6 shows a web service named marriageservice, which implements the marry method. It uses two person objects (as defined earlier) and modifies their attributes accordingly. (The download part of this Code contains the ASP. NET page attached to this example .)

If you choose to use XML in your client script, this option is still available. Microsoft. web. script. the services namespace also has a new property named scriptmethod, which has the responseformat feature, which can be set to JSON or XML (default value: JSON ).

namespace PS            {            [ScriptService]            [WebService(Namespace = "http://pluralsight.com/ws")]            [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]            public class StockQuoteService : WebService            {            [WebMethod]            public int GetStockQuote(string symbol)            {            return (new Random()).Next(0, 120);            }            }            }            

In this way, the serialized response will be:

<?xml version="1.0" encoding="utf-8"?><int>74</int>            

 

When you use the client JavaScript to call this method to process XML responses, you have to decide how to choose. This is useful if you plan to perform conversion on it, or you are already using MSXML.

Summary

It is worth noting that ASP. NET 2.0 Ajax extensions provides two pre-built services for accessing specific ASP. NET 2.0 application services through client code, which are profileservice and authenicationservice. With these two client proxies, you can set and retrieve configuration file values for a single client, and perform authentication completely in the client script (by default, the membership provider) and grant authentication cookies.

Despite many issues related to ASP. the discussion and demonstration of NET 2.0 Ajax extensions focuses on introducing beautiful controls that give user interfaces higher response capabilities, however, directly calling Web services using client Javascript is one of the most attractive and practical functions. With perfect. net Framework/JSON serialization program, and familiar. direct Integration of asmx web services, support for batch processing, and automatic generation of bridging with external web services, such comprehensive and in-depth support for Web Services may make this feature the most attractive feature of all features.

Send your questions and comments to Fritz to xtrmasp@microsoft.com ..

New: getting e the sample code online!-Or-Code download location:Extremeaspnet2007_01.exe (160kb)
Fritz onionOne of the founders of Microsoft. NET training provider pluralsight, is responsible for web development courses. Fritz is the author of essential ASP. NET (Addison Wesley, 2003) and essential ASP. NET 2.0 (Addison Wesley, 2006. You can contact him through pluralsight.com/fritz.
From January 2007 journal msdn magazine.
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.