如何使用ASP.NET AJAX訪問Web Services

來源:互聯網
上載者:User

使用用戶端script調用ASP.NET Web services (.asmx)和Windows Communication Foundation(WCF) services(.svc).指令碼引用是自動添加到頁面上的,並且他們自動產生Web service proxy類,你就從這裡使用用戶端指令碼調用Web service.

你還能訪問ASP.NET Web Servicce 不使用ASP.NET AJAX 服務端控制項(如,如果你使用不同的Web開發環境).這樣做,在頁面上你能動手包括引用Microsoft AJAX Library,引用指令檔,並且相應自己的Web service.在運行時,ASP.NET產生代理類調用服務.

ASP.NET Web services是組件下的一個方法調用HTTP.在下面你學習怎樣建立一個Web service和怎樣使用用戶端指令碼在一個AJAX-enabled Web application中調用WebSerice.

Using Web Services in ASP.NET AJAX

其實ASP.NET AJAX使用用戶端指令碼調用服務,這個服務中既有自己定義的服務也有構建在應用程式服務.應用程式服務在ASP.NET AJAX 中也有所他提供,並包括authentication, roles, and profile services.

在ASP.NET Web Services也自訂建立Web Services,或Windows Communication Foundation (WCF) services (.svc services).

一、使用情境

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

a. 如果你已經建立WCF服務,你能添加進入終端的AJAX-enabled Web pages中允許訪問服務;

b. 如果你已經建立ASP.NET Web (.asmx) services,你能修改他們允許使用指令碼訪問同樣的服務;

c. 如果你要使用ASP.NET AJAX Web pages上使用指令碼訪問你自己建立的自訂服務.你能像WCF service或an ASP.NET Web service樣實現它;

d. 你能使用ASP.NET application構建的services去訪問AJAX-enabled Web page使用者的authentication, roles, and profile的資訊。

三、案例

下面是如何調用ASP.NET和WCF服務.從用戶端指令碼調用應用程式服務是提供在其他部分.

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

.NET Framework 授權你使用用戶端瀏覽器非同步呼叫ASP.NET Web services(.asmx)方法.在頁面能調用基於服務端方法不需要postback和不重新整理頁面.因為只有資料在用戶端與服務端傳輸.

<%@ 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>

下面是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用戶端產生HTTP請求  

你還能最低層級的使用用戶端指令碼調用Web service.如果你有管理communication layer或調查來服務端的發送資料.你就使用WebRequest類去調用Web服務.

下面是怎樣使用WebRequest對象實現GET和POST Web請求串連詳細指定的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() + "]" + "
";

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

(3)Calling WCF Service Operations in AJAX

你能使用指令碼非同步呼叫調用 Windows Communication Foundation (WCF) services (.svc).下面是怎樣調用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.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; }
}
}

}

二、背景

在頁面上的交流使用通過一個Web service communication層,使用AJAX技術產生Web service調用.資料在用戶端和服務端非同步交換,特別是在JSON格式上.

(1)Client-Server Communication for AJAX Clients

在AJAX-enabled Web pages上,瀏覽器向服務端製造一個初始化請求,並且為資料並發非同步請求Web services.客戶交流的主要元素是從服務端下載proxy類和core client-script library.服務端交流的主要元素是handlers和自訂services.下面圖片顯示這些元素在服務端與用戶端之間交流被調用的情況.

(2)AJAX Client Architecture

瀏覽器被使用proxy類調用Web service方法.一個proxy(代理)類是在服務端自動產生的並且在頁面載入時下載到瀏覽器.這個代理類提供一個用戶端對象呈現暴露一個Web serice的方法.

調用一個Web service方法,用戶端指令碼調用相應的代理類方法.而且調用是非同步,是通過XMLHTTP對象.

Web service communication layer包括允許代理類產生服務調用的指令碼類型庫.

在代理服務類裡面的代碼和在核心Web Service交流層隱藏XMLHTTP的複雜性和不同瀏覽器的複雜性.簡化用戶端指令碼調用Web service.

(1)使用HTTP POST verb調用Web services.一個POST請求已經有一個包括瀏覽器發送到服務端的資料的主體.它沒有大小的限制.因此,當資料大小超過一個GET 請求的大小時候你仍然能使用POST請求.在用戶端serializes請求進入JSON格式並且發送像POST資料樣的到服務端.服務端deserializesJSON資料進入.NET Framework類型並製造真正的Web service調用.在這個期間響應,服務端serializes或傳回值和並返回到用戶端,在用戶端通過deserializes他們成為JavaScript objects.

(2)使用HTTP GET verb調用Web services.類似一個POST請求的功能.

a:這個cilent使用一個查詢字串發送到參數到服務端.

b:一個GET請求能一次只能調用調用一個Web service方法要使用ScriptMethodAttribute attribute標記一下.

c:資料大小被限制就在於瀏覽允許URL的長度上.

下面是顯示ASP.NET AJAX client 架構:

用戶端架構包括在library裡面的Web service communication layer和為服務下載到頁面上的代理類.下面是單個元素的詳細介紹:

a. Custom Service Proxy Classes:這些由服務端自動產生並下載到用戶端指令碼組成的.代理類為在頁面上使用WCF和ASMX中提供一個對象(那是,他們在ScriptManager control 的ServiceReferences中為每一個項提供元素).

b. Authentication Proxy Class.Authentication Proxy Class由服務端的authentication 應用程式服務產生.它允許使用者登陸或登出通過JavaScript做這件事情不需要往返伺服器端.

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

d. Profile Proxy Class:ProfileService Class.是由server ProfileService application service產生.它允許你目前使用者的資料資訊到達用戶端通過JavaScript做這件事情不需要往返伺服器端.

e. Page Methods Proxy Class:為在ASP.NET頁面上用戶端指令碼調用靜態方法提供底層架構.如果他們是Web service方法.

f. Web Service Communication Layer.這是一個庫包括用戶端指令碼類型.這些類型允許瀏覽器與伺服器端使用服務交流.他們還保護用戶端應用程式設定的複雜性.和維護用戶端和服務端的非同步交流.他們封裝瀏覽器提供非同步相容的XMLHTTP對象.並且授權使用得用戶端應用程式不受瀏覽器的約束.下面主要Web service communication layer元素.

(1)WebRequest: 提供用戶端功能產生一個Web ruquest.

(2)WebRequestManager: 這個是使用關聯執行對象的WebRequest object管理Web requests 發行的流程.

(3)XmlHttpExecutor:使用瀏覽器的XMLHTTP製造一個非同步網路請求.

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

(5)XML Serialization:Web service communication layer支援XML serialization 對SOAP請求 Web services和從一個JSON請求一個Web service返回XML類型.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.