How to use ASP. NET ajax to access web services

Source: Internet
Author: User
Tags javascript eval

Use a client script to call ASP. net web services (. asmx and Windows Communication Foundation (WCF) services (. SVC ). script Reference is automatically added to the page, and they automatically generate the Web Service proxy class, you can use the client script to call the Web service from here.

You can also access ASP. net web servicce does not use ASP. net Ajax server controls (for example, if you use different web development environments ). in this way, you can reference the Microsoft Ajax library, reference the script file, and configure your own web service. ASP. net generate proxy class call service.

ASP. NET web services is a method called HTTP under the component. Next you will learn how to create a web service and how to use client scripts to call webserice in an Ajax-enabled web application.

Using Web Services in ASP. NET Ajax

In fact, Asp.. Net Ajax uses client scripts to call the service. This service includes both the services defined by the user and the application services. application Service in ASP. net Ajax, including authentication, roles, and profile services.

You can also create Web Services in ASP. NET web services or Windows Communication Foundation (WCF) services (. SVC services ).

I. Application scenarios

You use WCF and ASP. NET with the following case:

A. If you have created a WCF Service, you can add it to the Ajax-enabled web pages page of the terminal to allow access to the service;

B. If you have created ASP. NET web (. asmx) services, you can modify them to allow scripts to access the same service;

C. If you want to use a script on ASP. NET Ajax web pages to access your own custom service, you can implement it like a WCF Service or an ASP. NET web service;

D. You can use the services built by ASP. NET application to access the authentication, roles, and profile information of the Ajax-enabled web page user.

Iii. Examples

The following describes how to call ASP. NET and WCF services. Calling application services from client scripts is provided in other sections.

(1) Use ajax to call the Web service method.

. Net Framework authorizes you to use the client browser to asynchronously call ASP. net web services (. asmx) method. the server-based method can be called on the page without the need for PostBack or refreshing the page. because only data is transmitted between the client and the server.

<%@ Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html >    <head id="Head1" runat="server">        <style type="text/css">            body {  font: 11pt Trebuchet MS;                    font-color: #000000;                    padding-top: 72px;                    text-align: center }            .text { font: 8pt Trebuchet MS }        </style>        <title>Simple Web Service</title>            <script type="text/javascript">            // This function calls the Web Service method.              function GetServerTime()            {                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);            }            // This is the callback function that            // processes the Web Service return value.            function OnSucceeded(result)            {                var RsltElem = document.getElementById("Results");                RsltElem.innerHTML = result;            }        </script>    </head>    <body>        <form id="Form1" runat="server">         <asp:ScriptManager runat="server" ID="scriptManager">                <Services>                    <asp:ServiceReference path="ServerTime.asmx" />                </Services>            </asp:ScriptManager>            <div>                <h2>Server Time</h2>                    <p>Calling a service that returns the current server time.</p>                    <input id="EchoButton" type="button"                         value="GetTime" onclick="GetServerTime()" />            </div>        </form>        <hr/>        <div>            <span id="Results"></span>        </div>       </body></html>

Below is the WebService

<% @ WebService Language = "C #" class = "samples. ASPnet. servertime" %>

Using system;
Using system. Web;
Using system. Web. Services;
Using system. xml;
Using system. Web. Services. Protocols;
Using system. Web. Script. Services;

Namespace samples. ASPnet
{

[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
[Scriptservice]
Public class servertime: system. Web. Services. WebService
{

[Webmethod]
Public String getservertime ()
{
Return string. Format ("the server time is {0 }.",
Datetime. Now );

}

}

}

(2) generating HTTP requests from the Ajax Client

You can also use client scripts to call web services at the lowest level. If you manage the communication layer or investigate data sent by the server, you can use the webrequest class to call Web Services.

The following describes how to use the webrequest object to implement the URL specified in detail for the get and Post Web requests.

// Connectingendpoints. js

VaR resultelement;

Function pageload ()
{
Resultelement = $ get ("resultid ");
}

// This function performs a get Web request.
Function getwebrequest ()
{
Alert ("grouping Ming get Web request .");

// Instantiate a webrequest.
VaR wrequest = new SYS. net. webrequest ();

// Set the request URL.
Wrequest. set_url ("gettarget.htm ");
Alert ("target URL: gettarget.htm ");

// Set the request verb.
Wrequest. set_httpverb ("get ");

// Set the request callback function.
Wrequest. add_completed (onwebrequestcompleted );

// Clear the results area.
Resultelement. innerhtml = "";

// Execute the request.
Wrequest. Invoke ();
}

// This function performs a Post Web request.
Function postwebrequest ()
{
Alert ("padding Ming Post Web request .");

// Instantiate a webrequest.
VaR wrequest = new SYS. net. webrequest ();

// Set the request URL.
Wrequest. set_url ("posttarget. aspx ");
Alert ("target URL: posttarget. aspx ");

// Set the request verb.
Wrequest. set_httpverb ("Post ");

// Set the request handler.
Wrequest. add_completed (onwebrequestcompleted );

// Set the body for he post.
VaR requestbody =
"Message = hello! Do you hear me? ";
Wrequest. set_body (requestbody );
Wrequest. get_headers () ["Content-Length"] =
Requestbody. length;

// Clear the results area.
Resultelement. innerhtml = "";

// Execute the request.
Wrequest. Invoke ();
}

// This callback function processes
// Request return values. It is called Asynchronously
// By the current executor.
Function onwebrequestcompleted (Executor, eventargs)
{
If (Executor. get_responseavailable ())
{
// Clear the previous results.

Resultelement. innerhtml = "";

// Display Web Request status.
Resultelement. innerhtml + =
"Status: [" + executor. get_statuscode () + "" +
Executor. get_statustext () + "]" +"
";

// Display Web request headers.
Resultelement. innerhtml + =
"Headers :";

Resultelement. innerhtml + =
Executor. getAllResponseHeaders () +"
";

// Display Web Request body.
Resultelement. innerhtml + =
"Body :";

If (document. All)
Resultelement. innertext + =
Executor. get_responsedata ();
Else
Resultelement. textcontent + =
Executor. get_responsedata ();
}

}
If (typeof (sys )! = "# Ff0000") SYS. application. policyscriptloaded ();

(3) Calling WCF Service Operations in Ajax

You can use scripts to call windows Communication Foundation (WCF) services (. SVC) asynchronously. The following describes how to call windows Communication Foundation (WCF) Services

<% @ Page Language = "C #" autoeventwireup = "true" %>

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML>
<Head runat = "server">
<Style type = "text/CSS">
Body {Font: 11pt trebuchet MS;
Font-color: #000000;
Padding-top: 72px;
Text-align: Center}

. Text {Font: 8pt trebuchet MS}
</Style>
<Title> simple WCF Service page </title>

</Head>
<Body>
<Form ID = "form1" runat = "server">
<Asp: scriptmanager id = "scriptmanager1" runat = "server">
<Services>
<Asp: servicereference
Path = "simpleservice. svc/WS"/>
</Services>
<Scripts>
<Asp: scriptreference Path = "service. js"/>
</Scripts>
</ASP: scriptmanager>

<Div>
<H2> simple WCF Service </H2>
<Input type = 'button 'name = "clickme" value = "greetings"
Onclick = "javascript: onclick ()"/>
<Input type = 'button 'name = "clickme2" value = "greetings2"
Onclick = "javascript: onclick2 ()"/>
<HR/>
<Div>
<Span id = "Results"> </span>
</Div>
</Div>

</Form>
</Body>
</Html>

VaR serviceproxy;

Function pageload ()
{
Serviceproxy = new isimpleservice ();
Serviceproxy. set_defaultsucceededcallback (succeededcallback );
}

Function onclick ()
{
// Var myservice = new isimpleservice ();
Serviceproxy. helloworld1 ("George ");
}

Function onclick2 ()
{
VaR Dc = new datacontracttype ();
DC. firstname = "George ";
DC. lastname = "Washington ";
Serviceproxy. helloworld2 (DC );
}

// This is the callback function that
// Processes the Web service return value.
Function succeededcallback (result, usercontext, methodname)
{
VaR rsltelem = Document. getelementbyid ("Results ");
Rsltelem. innerhtml = Result + "from" + methodname + ".";
}
If (typeof (sys )! = "Undefined") SYS. application. policyscriptloaded ();

Using system;
Using system. Web;
Using system. collections;
Using system. Collections. Generic;
Using system. Threading;
Using system. xml;
Using system. xml. serialization;
Using system. text;
Using system. IO;
Using system. runtime. serialization;
Using system. servicemodel;
Using system. servicemodel. description;
Using system. servicemodel. Dispatcher;
Using system. servicemodel. channels;
Using system. servicemodel. activation;

// This a WCF Service which consists of a contract,
// Defined below as isimpleservice, and datacontracttype,
// A class which implements that interface, see simpleservice,
// And configuration entries that specify behaviors associated
// That implementation (see <system. servicemodel> in Web. config)

Namespace ASPnet. Samples
{
[Servicecontract ()]
Public interface isimpleservice
{
[Operationcontract]
String helloworld1 (string value1 );
[Operationcontract]
String helloworld2 (datacontracttype datacontractvalue1 );
}

[Servicebehavior (includeexceptiondetailinfaults = true)]
[Aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode. Allowed)]
Public class simpleservice: isimpleservice
{
Public simpleservice ()
{}

Public String helloworld1 (string value1)
{
Return "hello" + value1;
}
Public String helloworld2 (datacontracttype datacontractvalue1)
{
Return "hello" + datacontractvalue1.firstname +
"" + Datacontractvalue1.lastname;
}
}

[Datacontract]
Public class datacontracttype
{
String firstname;
String lastname;

[Datamember]
Public String firstname
{
Get {return firstname ;}
Set {firstname = value ;}
}
[Datamember]
Public String lastname
{
Get {return lastname ;}
Set {lastname = value ;}
}
}

}

Ii. Background

Communication on the page uses a web service communication layer to generate Web service calls using Ajax technology. Data is asynchronously exchanged between the client and the server, especially in the JSON format.

(1) client-server communication for Ajax clients

On Ajax-enabled web pages, the browser creates an initialization request to the server and sends a concurrent asynchronous request to Web Services for data. the main elements of customer communication are to download the proxy class and core client-script library from the server. the main elements of server-side communication are handlers and custom services. the following figure shows the call of these elements between the server and the client.

(2) Ajax client architecture

The browser uses the proxy class to call the Web service method. A proxy class is automatically generated on the server and downloaded to the browser during page loading. this proxy class provides a client object to expose a web serice method.

When a web service method is called, the client script calls the corresponding proxy method, and the call is asynchronous, it is through the XMLHTTP object.

The Web service communication layer includes a script library that allows the proxy class to generate service calls.

The code in the proxy service class and the complexity of XMLHTTP and the complexity of different browsers are hidden in the core web service communication layer, which simplifies client script calls to web service.

(1) Use http post verb to call Web Services. a POST request already has a subject that includes the data sent from the browser to the server. it has no size limit. therefore, when the data size exceeds the size of a GET request, you can still use the POST request. the serializes request on the client enters the JSON format and sends a post data sample to the server. the server deserializesjson data enters. net Framework type and make real Web service calls. during this period, the server serializes or return values and return them to the client. In the client, they become JavaScript objects through deserializes.

(2) Use http get verb to call Web Services. Similar to the function of a POST request.

A: This cilent uses a query string to send the request to the server.

B: One GET request can only call one web service method at a time. Use scriptmethodattribute attribute to mark it.

C: The data size is limited by the length of the URL allowed for browsing.

The following shows the architecture of ASP. NET Ajax client:

The client architecture includes the Web service communication layer in the library and the proxy class for downloading the service to the page. The following is a detailed introduction of a single element:

A. custom Service proxy classes: these scripts are automatically generated by the server and downloaded to the client. the proxy class provides an object for using WCF and asmx on the page (that is, they provide elements for each item in the servicereferences of scriptmanager control ).

B. Authentication Proxy class. Authentication Proxy class is generated by the authentication application service on the server side. It allows users to log on or log off to the server without going back and forth to the server through JavaScript.

C. role proxy class: roleservice proxy class is generated by the server roles application service. it allows you to group users and groups users into a unit. You do not need to go back and forth to the server through JavaScript. this can be used to authorize or deny access to server resources.

D. Profile proxy class: profileservice class. It is generated by the server profileservice Application Service. It allows your current user's information to arrive at the client and does not need to be transferred to or from the server through JavaScript.

E. Page Methods proxy class: provides the underlying architecture for client scripts to call static methods on ASP. NET pages if they are Web service methods.

F. web service communication layer. this is a library that includes the client script type. these types allow the browser to communicate with the server through services. they also protect the complexity of client application settings. and maintain asynchronous communication between the client and the server. they encapsulate browsers to provide asynchronous and compatible XMLHTTP objects. the authorized client application is not restricted by the browser. the following are the main web service communication layer elements.

(1) webrequest: Provides the client function to generate a web ruquest.

(2) webrequestmanager: This is the process for managing the Web requests release using the webrequest object of the associated execution object.

(3) xmlhttpexecutor: Create an Asynchronous Network request using XMLHTTP of the browser.

(4) JSON serialization: This is the JSON format for serializes JavaScript objects. You can deserialization using Javascript eval function.

(5) XML serialization: the Web service communication layer supports XML serialization to return the XML type to the SOAP request web services and to a web service from a JSON request.

 

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.