ASP.NET中怎么利用AJAX訪問WebServices

ASP.NET中怎么利用AJAX訪問Web Services,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

公司主營業(yè)務(wù):做網(wǎng)站、成都網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)推出蚌山免費(fèi)做網(wǎng)站回饋大家。

Web Services


使用客戶端script調(diào)用ASP.NET Web services (.asmx)和Windows Communication Foundation(WCF) services(.svc).腳本引用是自動(dòng)添加到頁面上的,并且他們自動(dòng)產(chǎn)生Web service proxy類,你就從這里使用客戶端腳本調(diào)用Web service.

你還能訪問ASP.NET Web Servicce 不使用ASP.NET AJAX 服務(wù)端控件(如,如果你使用不同的Web開發(fā)環(huán)境).這樣做,在頁面上你能動(dòng)手包括引用Microsoft AJAX Library,引用腳本文件,并且相應(yīng)自己的Web service.在運(yùn)行時(shí),ASP.NET產(chǎn)生代理類調(diào)用服務(wù).

ASP.NET Web services是組件下的一個(gè)方法調(diào)用HTTP.在下面你學(xué)習(xí)怎樣創(chuàng)建一個(gè)Web service和怎樣使用客戶端腳本在一個(gè)AJAX-enabled Web application中調(diào)用WebSerice.

Using Web Services in ASP.NET AJAX

其實(shí)ASP.NET AJAX使用客戶端腳本調(diào)用服務(wù),這個(gè)服務(wù)中既有自己定義的服務(wù)也有構(gòu)建在應(yīng)用程序服務(wù).應(yīng)用程序服務(wù)在ASP.NET AJAX 中也有所他提供,并包括authentication, roles, and profile services.

在ASP.NET Web Services也自定義創(chuàng)建Web Services,或Windows Communication Foundation (WCF) services (.svc services).

一、使用場景


你使用WCF和ASP.NET有下面case:

a. 如果你已經(jīng)創(chuàng)建WCF服務(wù),你能添加進(jìn)入終端的AJAX-enabled Web pages中允許訪問服務(wù);

b. 如果你已經(jīng)創(chuàng)建ASP.NET Web (.asmx) services,你能修改他們?cè)试S使用腳本訪問同樣的服務(wù);

c. 如果你要使用ASP.NET AJAX Web pages上使用腳本訪問你自己創(chuàng)建的自定義服務(wù).你能像WCF service或an ASP.NET Web service樣實(shí)現(xiàn)它;

d. 你能使用ASP.NET application構(gòu)建的services去訪問AJAX-enabled Web page用戶的authentication, roles, and profile的信息。

二、背景


在頁面上的交流使用通過一個(gè)Web service communication層,使用AJAX技術(shù)產(chǎn)生Web service調(diào)用.數(shù)據(jù)在客戶端和服務(wù)端異步交換,特別是在JSON格式上.

(1)Client-Server Communication for AJAX Clients

在AJAX-enabled Web pages上,瀏覽器向服務(wù)端制造一個(gè)初始化請(qǐng)求,并且為數(shù)據(jù)并發(fā)異步請(qǐng)求Web services.客戶交流的主要元素是從服務(wù)端下載proxy類和core client-script library.服務(wù)端交流的主要元素是handlers和自定義services.下面圖片顯示這些元素在服務(wù)端與客戶端之間交流被調(diào)用的情況.

ASP.NET中怎么利用AJAX訪問Web Services

(2)AJAX Client Architecture

瀏覽器被使用proxy類調(diào)用Web service方法.一個(gè)proxy(代理)類是在服務(wù)端自動(dòng)產(chǎn)生的并且在頁面加載時(shí)下載到瀏覽器.這個(gè)代理類提供一個(gè)客戶端對(duì)象呈現(xiàn)暴露一個(gè)Web serice的方法.

調(diào)用一個(gè)Web service方法,客戶端腳本調(diào)用相應(yīng)的代理類方法.而且調(diào)用是異步的,是通過XMLHTTP對(duì)象.

Web service communication layer包括允許代理類產(chǎn)生服務(wù)調(diào)用的腳本類型庫.

在代理服務(wù)類里面的代碼和在核心Web Service交流層隱藏XMLHTTP的復(fù)雜性和不同瀏覽器的復(fù)雜性.簡化客戶端腳本調(diào)用Web service.

(1)使用HTTP POST verb調(diào)用Web services.一個(gè)POST請(qǐng)求已經(jīng)有一個(gè)包括瀏覽器發(fā)送到服務(wù)端的數(shù)據(jù)的主體.它沒有大小的限制.因此,當(dāng)數(shù)據(jù)大小超過一個(gè)GET 請(qǐng)求的大小時(shí)候你仍然能使用POST請(qǐng)求.在客戶端serializes請(qǐng)求進(jìn)入JSON格式并且發(fā)送像POST數(shù)據(jù)樣的到服務(wù)端.服務(wù)端deserializesJSON數(shù)據(jù)進(jìn)入.NET Framework類型并制造真正的Web service調(diào)用.在這個(gè)期間響應(yīng),服務(wù)端serializes或返回值和并返回到客戶端,在客戶端通過deserializes他們成為JavaScript objects.

(2)使用HTTP GET verb調(diào)用Web services.類似一個(gè)POST請(qǐng)求的功能.

a:這個(gè)cilent使用一個(gè)查詢字符串發(fā)送到參數(shù)到服務(wù)端.

b:一個(gè)GET請(qǐng)求能一次只能調(diào)用調(diào)用一個(gè)Web service方法要使用ScriptMethodAttribute attribute標(biāo)記一下.

c:數(shù)據(jù)大小被限制就在于瀏覽允許URL的長度上.

下面是顯示ASP.NET AJAX client 架構(gòu):

ASP.NET中怎么利用AJAX訪問Web Services

客戶端架構(gòu)包括在library里面的Web service communication layer和為服務(wù)下載到頁面上的代理類.下面是單個(gè)元素的詳細(xì)介紹:

a. Custom Service Proxy Classes:這些由服務(wù)端自動(dòng)產(chǎn)生并下載到客戶端腳本組成的.代理類為在頁面上使用WCF和ASMX中提供一個(gè)對(duì)象(那是,他們?cè)赟criptManager control 的ServiceReferences中為每一個(gè)項(xiàng)提供元素).

b. Authentication Proxy Class.Authentication Proxy Class由服務(wù)端的authentication 應(yīng)用程序服務(wù)產(chǎn)生.它允許用戶登陸或注銷通過JavaScript做這件事情不需要往返服務(wù)器端.

c. Role Proxy Class:RoleService proxy Class是由server roles application service產(chǎn)生.它允許你分組用戶和將用戶分組成一個(gè)單元,通過JavaScript做這件事情不需要往返服務(wù)器端.這能使用在授權(quán)或拒絕訪問服務(wù)端資源.

d. Profile Proxy Class:ProfileService Class.是由server ProfileService application service產(chǎn)生.它允許你當(dāng)前用戶的資料信息到達(dá)客戶端通過JavaScript做這件事情不需要往返服務(wù)器端.

e. Page Methods Proxy Class:為在ASP.NET頁面上客戶端腳本調(diào)用靜態(tài)方法提供底層架構(gòu).如果他們是Web service方法.

f. Web Service Communication Layer.這是一個(gè)庫包括客戶端腳本類型.這些類型允許瀏覽器與服務(wù)器端使用服務(wù)交流.他們還保護(hù)客戶端應(yīng)用程序設(shè)置的復(fù)雜性.和維護(hù)客戶端和服務(wù)端的異步交流.他們封裝瀏覽器提供異步兼容的XMLHTTP對(duì)象.并且授權(quán)使用得客戶端應(yīng)用程序不受瀏覽器的約束.下面主要Web service communication layer元素.

(1)WebRequest: 提供客戶端功能產(chǎn)生一個(gè)Web ruquest.

(2)WebRequestManager: 這個(gè)是使用關(guān)聯(lián)執(zhí)行對(duì)象的WebRequest object管理Web requests 發(fā)行的流程.

(3)XmlHttpExecutor:使用瀏覽器的XMLHTTP制造一個(gè)異步網(wǎng)絡(luò)請(qǐng)求.

(4)JSON Serialization:這是serializes JavaScript objects成為JSON格式.使用JavaScript eval function就能Deserialization.

(5)XML Serialization:Web service communication layer支持XML serialization 對(duì)SOAP請(qǐng)求 Web services和從一個(gè)JSON請(qǐng)求一個(gè)Web service返回XML類型.

三、事例


下面是如何調(diào)用ASP.NET和WCF服務(wù).從客戶端腳本調(diào)用應(yīng)用程序服務(wù)是提供在其他部分.

(1)使用AJAX調(diào)用Web Service方法.

.NET Framework 授權(quán)你使用客戶端瀏覽器異步調(diào)用ASP.NET Web services(.asmx)方法.在頁面能調(diào)用基于服務(wù)端方法不需要postback和不刷新頁面.因?yàn)橹挥袛?shù)據(jù)在客戶端與服務(wù)端傳輸.

<%@ 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>
                <h3>Server Time</h3>
                    <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>

下面是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)從AJAX客戶端產(chǎn)生HTTP請(qǐng)求  

你還能最低級(jí)別的使用客戶端腳本調(diào)用Web service.如果你有管理communication layer或調(diào)查來服務(wù)端的發(fā)送數(shù)據(jù).你就使用WebRequest類去調(diào)用Web服務(wù).

下面是怎樣使用WebRequest對(duì)象實(shí)現(xiàn)GET和POST Web請(qǐng)求連接詳細(xì)指定的URLs.

// ConnectingEndPoints.js

var resultElement;

function pageLoad()
{
resultElement = $get("ResultId");
}

// This function performs a GET Web request.
function GetWebRequest()
{
alert("Performing 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("Performing 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 the
// 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() + "]" + "<br/>";

        // Display Web request headers.
resultElement.innerHTML +=
"Headers: ";

       resultElement.innerHTML +=
executor.getAllResponseHeaders() + "<br/>";

        // 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.notifyScriptLoaded();

(3)Calling WCF Service Operations in AJAX

你能使用腳本異步調(diào)用調(diào)用 Windows Communication Foundation (WCF) services (.svc).下面是怎樣調(diào)用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>
<h3>Simple WCF Service</h3>
<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.notifyScriptLoaded();


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 with
// 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; }
}
}

}

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。

當(dāng)前名稱:ASP.NET中怎么利用AJAX訪問WebServices
鏈接URL:http://bm7419.com/article2/jcseoc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、定制開發(fā)、動(dòng)態(tài)網(wǎng)站App開發(fā)、服務(wù)器托管、電子商務(wù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)