在VS2005中,Web服務代理的配置可以使用兩種方法來自動完成,即引用Web服務自動完成,或者使用wsdl.exe工具自動完成。
Web服務代理用於用戶端訪問XML Web Services。在用戶端使用Web引用時,VS2005將自動建立一個XML Web Services代理類,並把該類添加到項目中。
預設情況下,XML Web Services代理類使用靜態URL,指向引用XML Web Services的URL。當應用程式在web.config檔案中指定了appSettings元素,Web服務代理可以從該元素指定的內容指向動態URL。下面說明如何在web.config中指定appSettings元素,以指定XML Web Services代理的URL,代碼如下:
<appSettings>
<add key ="myApplication.myserver.Service" value="http://myServer/myXmlWebService.asmx"/>
</appSettings>
下面分別說明如何使用這兩種方法配置Web服務代理,步驟如下:
1、開啟VS2005 ,建立一個ASP.NET 的Web服務網站,命名為“myXmlWebService”.
2、開啟Services.cs檔案,編輯該檔案,代碼如下:
using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;[WebService(Namespace="http://tmpuri.org/")][WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]public class Service : System.Web.Services.WebService{ public Service() { } [WebMothed(Description="Web服務代理測試方法",EnableSession=true)] public string ServiceMethod() { return "Web 服務已調用。"; }}
3、按F5運行該Web服務
4、保持myXmlWebService網站的運行狀態,再次開啟VS2005,建立一個asp.net網站應用程式程式,命名為“myWebApp”.
5、在myWebApp網站路徑內添加Web引用,複製“myXmlWebService”運行網頁上顯示Service類操作類表的URL地址,粘貼到添加Web引用視窗的URL地址中,Web引用名保持“localhost”不變。
6、開啟web.Config檔案,VS2005為應用程式產生了appSetting節,代碼如下:
<configuratioin>
<appSettings>
<add key="localhost.Service" value="http://localhost:1662/myXmlWebService/Service.asmx"/>
...
</appSettings>
7、在Default.aspx檔案的設計介面上得空白處,雙擊滑鼠左鍵,編寫該頁面的Page_Load事件處理方法。代碼如下:
protected void Page_Load(object sender,EventArgs e)
{
Response.Write(new localhost.Service().ServiceMethod());
}
8、按F5運行網站應用程式程式,運行結果如下:
Web服務已調用。
9、在myXmlWebService網站解決方案中添加Web服務,命名為"wsdlService.asmx"。
10、在wsdlService.cs檔案中編輯程式,代碼如下
using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;[WebService(Namespace="http://tmpuri.org/")][WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]public class Service : System.Web.Services.WebService{ public Service() { } [WebMothed(Description="Web服務代理測試方法(wsdl)",EnableSession=true)] public string ServiceMethod() { return "wsdl-Web 服務已調用。"; }}
11、重新發布myXmlWebService網站,運行該網站。
12、保持myXmlWebService網站的運行,開發VS2005命令提示工具,進入myWebApp網站所在目錄,運行一下命令:
wsdl.exe /appsettingurlkey:local.wsdlService "http://localhost:1662/myXmlWebService/wsdlService.asmx"
13、在myWebApp網站所在的目錄下,添加asp.net檔案夾App_Code,將前面產生的wsdlService.cs檔案加入到該檔案夾中。
14、在Default.aspx檔案的設計介面上雙擊滑鼠左鍵,編寫Page_Load事件處理方法:
protected void Page_Load(object sender,EventArgs e)
{
Response.Write(new localhost.Service().ServiceMethod());
Response.Write(new wsdlService().wsdlServiceMehtod());
}
15、按F5運行程式,運行結果如下:
Web服務已調用。wsdl-Web服務已調用。
使用wsdl.exe產生的程式檔案和WebService上的程式檔案不同,該檔案包含的類繼承於SoapHttpClientProtocol類。在該類的建構函式中,使用appSettings中指定的URL建立類執行個體,如果appSettings沒有指定URL,則使用預設的URL建立類執行個體。SoapHttpClientProtocol類包含實現SOAP交換資訊協議的方法,通過這些方法,應用程式和Web服務能夠進行多種方式的資料交換。