589
技術社區[雲棲]
ASP.NET創建Web服務之設計方針
使用ASP.NET構造一個簡單的XMLWeb服務是相對容易的,然而,XMLWeb服務的真正的強大的功能隻有等你研究了基礎結構以後才能領悟。XMLWeb服務是建立在.NET框架和公共語言運行時間基礎上的。一個XMLWeb服務可以利用這些技術。例如,ASP.NET支持的性能、狀態管理和驗證全都可被用來構造XMLWeb服務。
XMLWeb服務的基礎結構是構建來符合象SOAP、XML和WSDL這樣的行業標準,並且它允許其他的平台的客戶端與XMLWeb服務互操作。隻要一個客戶端可以發送符合標準的SOAP消息、依據格式化的服務描述,那麼這個客戶端可以調用一個使用ASP.NET創建的XMLWeb服務(不管客戶端存在於何種平台)。
當你使用ASP.NET構造一個XMLWeb服務時,它自動支持客戶端使用SOAP、HTTP-GET和HTTP-POST協議通訊。即使HTTP-GET和HTTP-POST支持使用URL編碼的變量名/變量值對來傳送消息,支持這兩個協議的數據類型也沒有支持SOAP協議的數據類型豐富。在SOAP中,使用XML把數據傳送到XMLWeb服務或從XMLWeb服務取回消息,你可以使用支持豐富的數據類型集的XSD模式定義複雜的數據類型。使用ASP.NET構造一個XMLWeb服務的開發者不必明確地定義複雜的數據類型。他們可以隻構造一個管理類。ASP.NET處理定義到一個XSD模式的映射類和到XML數據的映射對象實例,以便通過網絡傳輸。
重要的是要注意XMLWeb服務並不能取代DCOM,我們應該說XMLWeb服務是跨越使用行業標準的平台通信的一種消息傳遞基礎結構。
因為ASP.NET提供了為XMLWeb服務內部工作的基礎結構,開發者可以集中精力來實現他們的特定的XMLWeb服務的功能。使用ASP.NET開發一個XMLWeb服務從下麵三步開始:
1.創建一個帶有.asmx擴展名的文件。
2.在這個文件裏麵,使用一條指令聲明XMLWeb服務。
3.定義組成XMLWeb服務功能的XMLWeb服務方法。
XMLWeb服務是一個強大的技術,用於提供可通過因特網變成訪問的服務。下麵的建議將幫助你創建高效的XMLWeb服務:
XMLWeb服務既支持同步的又支持異步的客戶端和存放XMLWeb服務的服務器之間的通信。在同步通信情況下,客戶端發送一個對服務的請求到服務主機服務器上等待響應。這防止客戶端在等待結果的時候,執行其它的操作。然而異步通信導致客戶端在等待相應的時候繼續處理其它的任務。客戶端在可用的時候響應服務請求的結果。
當你使用Web服務描述語言工具(Wsdl.exe)來創建你的代理類的時候,它產生類中的方法的標準的、同步版本和異步版本。異步版本由兩個方法組成,稱為Begin和End。Begin方法用於初始化XMLWeb服務,而End方法取得結果。
使用異步通信能夠改善係統使用率和避免客戶端在它等待XMLWeb服務結果的時候的延遲。
下麵的代碼示例顯示如何從一個客戶應用程序產生一個到XMLWeb服務的異步調用。
[C#]
<%@PageLanguage="C#"%> <%@ImportNamespace="System.Net"%> <html> <scriptlanguage="C#"runat="server"> voidEnterBtn_Click(ObjectSrc,EventArgsE) { MyMath.Mathmath=newMyMath.Math(); //CalltoAddXMLWebservicemethodasynchronously //andthenwaitforittocomplete. IAsyncResultresult= math.BeginAdd(Convert.ToInt32(Num1.Text), Convert.ToInt32(Num2.Text), null, null); //Waitforasynchronouscalltocomplete. result.AsyncWaitHandle.WaitOne(); //CompletetheasynchronouscalltoAddXMLWebservicemethod. floattotal=math.EndAdd(result); //DisplayresultsinaLabelcontrol. Total.Text="Total:"+total.ToString(); } </script> <body> <formaction="MathClient.aspx"runat=server> <fontface="Verdana"> Enterthetwonumbersyouwanttoaddandthenpress theTotalbutton. <p> Number1: <asp:textbox runat=server/> + Number2: <asp:textbox runat=server/> = <asp:button text="Total" OnClick="EnterBtn_Click" runat=server/> <p> <asp:labelrunat=server/> </font> </form> </body> </html> [VisualBasic] <%@PageLanguage="VB"%> <%@ImportNamespace="System.Net"%> <html> <scriptlanguage="VB"runat="server"> SubEnterBtn_Click(SrcAsObject,EAsEventArgs) DimmathAsNewMyMath.Math() 'CalltoAddXMLWebservicemethodasynchronously 'andthenwaitforittocomplete. DimresultAsIAsyncResult=_ math.BeginAdd(Convert.ToInt32(Num1.Text),_ Convert.ToInt32(Num2.Text),_ Nothing,_ Nothing) 'Waitforasynchronouscalltocomplete. result.AsyncWaitHandle.WaitOne() 'CompletetheasynchronouscalltoAddXMLWebservicemethod. DimaddtotalAsSingle=math.EndAdd(result) 'DisplayresultsinaLabelcontrol. Total.Text="Total:"&addtotal.ToString() EndSub </script> <body> <formaction="MathClient.aspx"runat=server> <fontface="Verdana"> Enterthetwonumbersyouwanttoaddandthenpress theTotalbutton. <p> Number1: <asp:textbox runat=server/> + Number2: <asp:textbox runat=server/> = <asp:button text="Total" OnClick="EnterBtn_Click" runat=server/> <p> <asp:labelrunat=server/> </font> </form> </body> </html> |
想獲得更多關於異步通信的信息,請參閱後麵的"和XMLWeb服務異步地通訊"。
通過因特網產生許多服務請求可能影響客戶應用程序的性能。當設計你的XMLWeb服務時,通過創建把有關信息集中在一起的方法可以有效利用服務請求。例如,假定你有一個XMLWeb服務,用來檢索一本書的信息。我們可以創建一個在一條服務請求中返回所有的信息的方法,來代替單獨的檢索書名、作者和出版社的方法。一次傳送大塊的信息比多次傳送小塊的信息更有效率。
下麵的代碼示例解釋如何把有關信息組織到單個XMLWeb服務方法中。
[C#]
<%@WebServiceLanguage="C#"Class="DataService"%> usingSystem; usingSystem.Data; usingSystem.Data.SqlClient; usingSystem.Web.Services; publicclassDataService{ [WebMethod] publicDataSetGetTitleAuthors(){ SqlConnectionmyConnection=newSqlConnection("PersistSecurityInfo=False;IntegratedSecurity=SSPI;server=localhost;database=pubs"); SqlDataAdaptermyCommand1=newSqlDataAdapter("select*fromAuthors",myConnection); SqlDataAdaptermyCommand2=newSqlDataAdapter("select*fromTitles",myConnection); DataSetds=newDataSet(); myCommand1.Fill(ds,"Authors"); myCommand2.Fill(ds,"Titles"); returnds; } } |
[VisualBasic]
<%@WebServiceLanguage="VB"Class="DataService"%> ImportsSystem ImportsSystem.Data ImportsSystem.Data.SqlClient ImportsSystem.Web.Services PublicClassDataService <WebMethod>_ PublicFunctionGetTitleAuthors()AsDataSet DimmyConnectionAsNewSqlConnection("PersistSecurityInfo=False;IntegratedSecurity=SSPI;server=localhost;database=pubs") DimmyCommand1AsNewSqlDataAdapter("select*fromAuthors",myConnection) DimmyCommand2AsNewSqlDataAdapter("select*fromTitles",myConnection) DimdsAsNewDataSet() myCommand1.Fill(ds,"Authors") myCommand2.Fill(ds,"Titles") Returnds EndFunction EndClass |
當設計你的XMLWeb服務時,請確保使用標準的麵向對象編程操作。使用封裝來隱藏實現細節。對於更複雜的XMLWeb服務,你可以使用繼承和多態性來再次使用代碼並簡化你的設計。
下麵的代碼示例顯示如何使用繼承來創建一個執行數學計算的XMLWeb服務。
[C#]
<%@WebServiceLanguage="C#"Class="Add"%> usingSystem; usingSystem.Web.Services; abstractpublicclassMathService:WebService { [WebMethod] abstractpublicfloatCalculateTotal(floata,floatb); } publicclassAdd:MathService { [WebMethod] overridepublicfloatCalculateTotal(floata,floatb) { returna+b; } } publicclassSubtract:MathService { [WebMethod] overridepublicfloatCalculateTotal(floata,floatb) { returna-b; } } publicclassMultiply:MathService { [WebMethod] overridepublicfloatCalculateTotal(floata,floatb) { returna*b; } } publicclassDivide:MathService { [WebMethod] overridepublicfloatCalculateTotal(floata,floatb) { if(b==0) return-1; else returna/b; } } |
[VisualBasic]
<%@WebServiceLanguage="VB"Class="Add"%> ImportsSystem ImportsSystem.Web.Services MustInheritPublicClassMathService:InheritsWebService <WebMethod>_ PublicMustOverrideFunctionCalculateTotal(aAsSingle,_ bAsSingle)AsSingle EndClass PublicClassAdd:InheritsMathService <WebMethod>PublicOverridesFunctionCalculateTotal(aAsSingle,bAsSingle)AsSingle Returna+b EndFunction EndClass PublicClassSubtract:InheritsMathService <WebMethod>PublicOverridesFunctionCalculateTotal(aAsSingle,bAsSingle)AsSingle Returna-b EndFunction EndClass PublicClassMultiply:InheritsMathService <WebMethod>PublicOverridesFunctionCalculateTotal(aAsSingle,bAsSingle)AsSingle Returna*b EndFunction EndClass PublicClassDivide:InheritsMathService <WebMethod>PublicOverridesFunctionCalculateTotal(aAsSingle,bAsSingle)AsSingle Ifb=0Then Return-1 Else Returna/b EndIf EndFunction EndClass |
使用輸出緩衝來改善你的XMLWeb服務的性能。當輸出緩衝開啟時,服務請求的結果被保存在輸出緩衝中一段指定的時間。如果一個類似的XMLWeb服務請求被產生,結果可以從緩衝中取得,而不用重新計算。這樣就通過減少XMLWeb服務服務器所需的處理來改善了XMLWeb服務的反饋時間。高速緩存可在客戶端和服務器兩者上執行。Duration屬性允許你指定高速緩衝保存XMLWeb服務輸出的時間。
在客戶端上使用輸出高速緩衝的指令是:
<%@OutputCacheDuration="60"%> |
下麵的代碼示例顯示如何在客戶應用程序上使用Duration屬性來指定輸出高速緩衝為60秒。
[C#]
<%@PageLanguage="C#"%> <%@ImportNamespace="System.Net"%> <%@OutputCacheDuration="60"VaryByParam="none"%> <html> <scriptlanguage="C#"runat="server"> voidEnterBtn_Click(ObjectSrc,EventArgse) { MyMath.Mathmath=newMyMath.Math(); //CalltheXMLWebservice. floattotal=math.Add(Convert.ToInt32(Num1.Text), Convert.ToInt32(Num2.Text)); //DisplaytheresultsinaLabelcontrol. Total.Text="Total:"+total.ToString(); } </script> <body> <formaction="MathClient.aspx"runat=server> <fontface="Verdana"> Enterthetwonumbersyouwanttoaddandpress theTotalbutton. <p> Number1: <asp:textboxrunat=server/> +Number2: <asp:textboxrunat=server/> =<asp:buttontext="Total"OnClick="EnterBtn_Click"runat=server/> <p> <asp:labelrunat=server/> </font> </form> </body> </html> |
[VisualBasic]
|
你還可以使用WebMethod屬性類的CacheDuration屬性來在服務器上允許高速緩衝。下麵的代碼示例顯示如何在XMLWeb服務方法上使用CacheDuration屬性來指定輸出高速緩衝為60秒。
[C#]
<%@WebServiceLanguage="C#"Class="MathService"%> usingSystem; usingSystem.Web.Services; publicclassMathService:WebService{ [WebMethod(CacheDuration=60)] publicfloatAdd(floata,floatb) { returna+b; } [WebMethod(CacheDuration=60)] publicfloatSubtract(floata,floatb) { returna-b; } [WebMethod(CacheDuration=60)] publicfloatMultiply(floata,floatb) { returna*b; } [WebMethod(CacheDuration=60)] publicfloatDivide(floata,floatb) { if(b==0)return-1; returna/b; } } |
[VisualBasic]
<%@WebServiceLanguage="VB"Class="MathService"%> ImportsSystem ImportsSystem.Web.Services PublicClassMathService InheritsWebService <WebMethod(CacheDuration:=60)>_ PublicFunctionAdd(aAsSingle,bAsSingle)AsSingle Returna+b EndFunction <WebMethod(CacheDuration:=60)>_ PublicFunctionSubtract(aAsSingle,bAsSingle)AsSingle Returna-b EndFunction <WebMethod(CacheDuration:=60)>_ PublicFunctionMultiply(aAsSingle,bAsSingle)AsSingle Returna*b EndFunction <WebMethod(CacheDuration:=60)>_ PublicFunctionDivide(aAsSingle,bAsSingle)AsSingle Ifb=0Then Return-1 EndIf Returna/b EndFunction EndClass |
當設計你的XMLWeb服務時,努力遵循如何格式化模式的結構。
XMLWeb服務使用SOAP作為主要的傳送和序列化協議。一個SOAP消息由一個可選擇的頭體和消息體組成。頭部分包含可以被Web服務器體係結構處理的信息。SOAP沒有定義任何頭。消息體部分包含由應用程序處理的信息,例如用於XMLWeb服務的參數或返回值。
提供用於你的XMLWeb服務的文檔,如一個靜態HTML文件,描述你的服務的操作和數據結構。還包括如何使用這個XMLWeb服務的示例。不要依靠服務描述或服務幫助頁麵作為你唯一的文檔。
最後更新:2017-04-02 00:06:35