您好,登錄后才能下訂單哦!
ASP.NET中怎么利用AJAX訪(fǎng)問(wèn)Web Services,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
Web Services
使用客戶(hù)端script調(diào)用ASP.NET Web services (.asmx)和Windows Communication Foundation(WCF) services(.svc).腳本引用是自動(dòng)添加到頁(yè)面上的,并且他們自動(dòng)產(chǎn)生Web service proxy類(lèi),你就從這里使用客戶(hù)端腳本調(diào)用Web service.
你還能訪(fǎng)問(wèn)ASP.NET Web Servicce 不使用ASP.NET AJAX 服務(wù)端控件(如,如果你使用不同的Web開(kāi)發(fā)環(huán)境).這樣做,在頁(yè)面上你能動(dòng)手包括引用Microsoft AJAX Library,引用腳本文件,并且相應(yīng)自己的Web service.在運(yùn)行時(shí),ASP.NET產(chǎn)生代理類(lèi)調(diào)用服務(wù).
ASP.NET Web services是組件下的一個(gè)方法調(diào)用HTTP.在下面你學(xué)習(xí)怎樣創(chuàng)建一個(gè)Web service和怎樣使用客戶(hù)端腳本在一個(gè)AJAX-enabled Web application中調(diào)用WebSerice.
Using Web Services in ASP.NET AJAX
其實(shí)ASP.NET AJAX使用客戶(hù)端腳本調(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).
一、使用場(chǎng)景
你使用WCF和ASP.NET有下面case:
a. 如果你已經(jīng)創(chuàng)建WCF服務(wù),你能添加進(jìn)入終端的AJAX-enabled Web pages中允許訪(fǎng)問(wèn)服務(wù);
b. 如果你已經(jīng)創(chuàng)建ASP.NET Web (.asmx) services,你能修改他們?cè)试S使用腳本訪(fǎng)問(wèn)同樣的服務(wù);
c. 如果你要使用ASP.NET AJAX Web pages上使用腳本訪(fǎng)問(wèn)你自己創(chuàng)建的自定義服務(wù).你能像WCF service或an ASP.NET Web service樣實(shí)現(xiàn)它;
d. 你能使用ASP.NET application構(gòu)建的services去訪(fǎng)問(wèn)AJAX-enabled Web page用戶(hù)的authentication, roles, and profile的信息。
二、背景
在頁(yè)面上的交流使用通過(guò)一個(gè)Web service communication層,使用AJAX技術(shù)產(chǎn)生Web service調(diào)用.數(shù)據(jù)在客戶(hù)端和服務(wù)端異步交換,特別是在JSON格式上.
(1)Client-Server Communication for AJAX Clients
在AJAX-enabled Web pages上,瀏覽器向服務(wù)端制造一個(gè)初始化請(qǐng)求,并且為數(shù)據(jù)并發(fā)異步請(qǐng)求Web services.客戶(hù)交流的主要元素是從服務(wù)端下載proxy類(lèi)和core client-script library.服務(wù)端交流的主要元素是handlers和自定義services.下面圖片顯示這些元素在服務(wù)端與客戶(hù)端之間交流被調(diào)用的情況.
(2)AJAX Client Architecture
瀏覽器被使用proxy類(lèi)調(diào)用Web service方法.一個(gè)proxy(代理)類(lèi)是在服務(wù)端自動(dòng)產(chǎn)生的并且在頁(yè)面加載時(shí)下載到瀏覽器.這個(gè)代理類(lèi)提供一個(gè)客戶(hù)端對(duì)象呈現(xiàn)暴露一個(gè)Web serice的方法.
調(diào)用一個(gè)Web service方法,客戶(hù)端腳本調(diào)用相應(yīng)的代理類(lèi)方法.而且調(diào)用是異步的,是通過(guò)XMLHTTP對(duì)象.
Web service communication layer包括允許代理類(lèi)產(chǎn)生服務(wù)調(diào)用的腳本類(lèi)型庫(kù).
在代理服務(wù)類(lèi)里面的代碼和在核心Web Service交流層隱藏XMLHTTP的復(fù)雜性和不同瀏覽器的復(fù)雜性.簡(jiǎn)化客戶(hù)端腳本調(diào)用Web service.
(1)使用HTTP POST verb調(diào)用Web services.一個(gè)POST請(qǐng)求已經(jīng)有一個(gè)包括瀏覽器發(fā)送到服務(wù)端的數(shù)據(jù)的主體.它沒(méi)有大小的限制.因此,當(dāng)數(shù)據(jù)大小超過(guò)一個(gè)GET 請(qǐng)求的大小時(shí)候你仍然能使用POST請(qǐng)求.在客戶(hù)端serializes請(qǐng)求進(jìn)入JSON格式并且發(fā)送像POST數(shù)據(jù)樣的到服務(wù)端.服務(wù)端deserializesJSON數(shù)據(jù)進(jìn)入.NET Framework類(lèi)型并制造真正的Web service調(diào)用.在這個(gè)期間響應(yīng),服務(wù)端serializes或返回值和并返回到客戶(hù)端,在客戶(hù)端通過(guò)deserializes他們成為JavaScript objects.
(2)使用HTTP GET verb調(diào)用Web services.類(lèi)似一個(gè)POST請(qǐng)求的功能.
a:這個(gè)cilent使用一個(gè)查詢(xún)字符串發(fā)送到參數(shù)到服務(wù)端.
b:一個(gè)GET請(qǐng)求能一次只能調(diào)用調(diào)用一個(gè)Web service方法要使用ScriptMethodAttribute attribute標(biāo)記一下.
c:數(shù)據(jù)大小被限制就在于瀏覽允許URL的長(zhǎng)度上.
下面是顯示ASP.NET AJAX client 架構(gòu):
客戶(hù)端架構(gòu)包括在library里面的Web service communication layer和為服務(wù)下載到頁(yè)面上的代理類(lèi).下面是單個(gè)元素的詳細(xì)介紹:
a. Custom Service Proxy Classes:這些由服務(wù)端自動(dòng)產(chǎn)生并下載到客戶(hù)端腳本組成的.代理類(lèi)為在頁(yè)面上使用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)生.它允許用戶(hù)登陸或注銷(xiāo)通過(guò)JavaScript做這件事情不需要往返服務(wù)器端.
c. Role Proxy Class:RoleService proxy Class是由server roles application service產(chǎn)生.它允許你分組用戶(hù)和將用戶(hù)分組成一個(gè)單元,通過(guò)JavaScript做這件事情不需要往返服務(wù)器端.這能使用在授權(quán)或拒絕訪(fǎng)問(wèn)服務(wù)端資源.
d. Profile Proxy Class:ProfileService Class.是由server ProfileService application service產(chǎn)生.它允許你當(dāng)前用戶(hù)的資料信息到達(dá)客戶(hù)端通過(guò)JavaScript做這件事情不需要往返服務(wù)器端.
e. Page Methods Proxy Class:為在ASP.NET頁(yè)面上客戶(hù)端腳本調(diào)用靜態(tài)方法提供底層架構(gòu).如果他們是Web service方法.
f. Web Service Communication Layer.這是一個(gè)庫(kù)包括客戶(hù)端腳本類(lèi)型.這些類(lèi)型允許瀏覽器與服務(wù)器端使用服務(wù)交流.他們還保護(hù)客戶(hù)端應(yīng)用程序設(shè)置的復(fù)雜性.和維護(hù)客戶(hù)端和服務(wù)端的異步交流.他們封裝瀏覽器提供異步兼容的XMLHTTP對(duì)象.并且授權(quán)使用得客戶(hù)端應(yīng)用程序不受瀏覽器的約束.下面主要Web service communication layer元素.
(1)WebRequest: 提供客戶(hù)端功能產(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類(lèi)型.
三、事例
下面是如何調(diào)用ASP.NET和WCF服務(wù).從客戶(hù)端腳本調(diào)用應(yīng)用程序服務(wù)是提供在其他部分.
(1)使用AJAX調(diào)用Web Service方法.
.NET Framework 授權(quán)你使用客戶(hù)端瀏覽器異步調(diào)用ASP.NET Web services(.asmx)方法.在頁(yè)面能調(diào)用基于服務(wù)端方法不需要postback和不刷新頁(yè)面.因?yàn)橹挥袛?shù)據(jù)在客戶(hù)端與服務(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客戶(hù)端產(chǎn)生HTTP請(qǐng)求
你還能最低級(jí)別的使用客戶(hù)端腳本調(diào)用Web service.如果你有管理communication layer或調(diào)查來(lái)服務(wù)端的發(fā)送數(shù)據(jù).你就使用WebRequest類(lèi)去調(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)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。