如何創(chuàng)建和使用Web Service代理類
2024-07-21 02:21:17
供稿:網(wǎng)友
 
 
如何創(chuàng)建和使用web service代理類
 
 web服務代理是支持.net的編程語言文件,由.net框架提供的wsdl工具自動生成。代理類不包含任何應用程序邏輯。相反,他包含關于如何傳遞參數(shù)和檢索結果的傳輸邏輯,還包含web服務中的方法及原型列表。代理類可以從任何wsdl文件創(chuàng)建。
 
 可以像訪問com對象一樣訪問web服務。要訪問web服務,需要從本地計算機上的web服務的wsdl文檔創(chuàng)建代理類。.net提供了名為wsdl.exe的工具以自動生成代理類文件。下面詳細說明其創(chuàng)建和使用過程:
 
1、 新建一個asp應用程序(#c)工程,工程名為teachshow,在teachshow工程中創(chuàng)建一個文件夾charpter8,在該文件夾下創(chuàng)建一個新的web服務,取名為:computer.asmx
2、 切換到代碼視圖,編寫下面的代碼:
[webmethod(description="用于相加運算", enablesession=false)]
 public int add(int a,int b)
 {
 return a+b;
 }
 
 [webmethod(description="用于相減運算", enablesession=false)]
 public int sub(int a,int b)
 {
 return a+b;
 }
 
 [webmethod(description="用于相乘運算", enablesession=false)]
 public int multi(int a,int b)
 {
 return a*b;
 }
 
 [webmethod(description="用于相除運算", enablesession=false)]
 public double devide(int a,int b)
 {
 return convert.todouble(a)/convert.todouble(b);
 
 3、按f5編譯整個工程(這一步一定要做,如果不做第4步無法實現(xiàn))
 
4、打開ms.net 2003的命令提示工具,輸入:c:/>wsdl http://localhost/teachshow/charpter8/firstanduse/computer.asmx /n:computernamespace,其中,computernamespace是自定義的命名空間。提示如下:
microsoft (r) web 服務描述語言實用工具
[microsoft (r) .net framework,版本 1.1.4322.573]
copyright (c) microsoft corporation 1998-2002. all rights reserved.
 
正在寫入文件“c:/computer.cs”。
 
5、注意,此時在c:盤(其實就是命令提示符的當前目錄)下生成一個和computer.asmx相同文件名的c#源文件computer.cs。
 
6、編譯computer.cs文件,在命令提示符下輸入如下命令:c:/>csc /out:computerdll.dll /t:library /r:system.web.services.dll c:/computer.cs。其中,/out:computerdll.dll是要輸出的dll文件,/t:library是輸出文件類型,/r:system.web.services.dll是要引用的組件,c:/computer.cs是第4步生成的c#文件。
 
7、此時,將會在c:盤下生成一個叫computerdll.dll的文件,要使用這個文件,必須復制到teachshow文件夾下的bin目錄下。默認情況下為:c:/inetpub/wwwroot/teachshow/bin。
 
8、新建一個名為testwsdl.aspx的web窗體文件,并添加一個引用,將剛才生成的computerdll.dll文件作為引用添加到工程中。
 
9、在testwsdl.aspx窗體的load事件中編寫代碼:
 computernamespace.computer com=new computernamespace.computer();
 this.response.write("和:"+com.add(45,65).tostring()+"
");
 this.response.write("減:"+com.sub(78,900).tostring()+"
");
 this.response.write("乘:"+com.multi(43,55).tostring()+"
");
 this.response.write("除:"+com.devide(1000,33).tostring());
 顯示結果:
和:110
減:978
乘:2365
除:30.3030303030303
 
 10、至此,程序完成。