Web Services
使用客戶端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的信息。
二、背景
在頁面上的交流使用通過一個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類型.
三、事例
下面是如何調用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() + "]" + "<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
你能使用腳本異步調用調用 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; }
}
}
}