C#建立Web Service
下面,我們看看如何C#建立Web Service
C#建立Web Service
1.在wwwroot目錄下建立一個叫做Webservice的目錄。
2.建立下面這樣一個文件:
- using System;
- using System.Web.Services;
- public class AddNumbers : WebService
- {
- [WebMethod]
- public int Add(int a, int b){
- int sum;
- sum = a + b;
- return sum;
- }
- }
3.將這個文件保存為AddService.asmx(asmx是擴(kuò)展名),保存到Webservice的目錄中
4.現(xiàn)在我們建立了Web服務(wù),已經(jīng)準(zhǔn)備好客戶端使用
5.現(xiàn)在,你可以用下面的URL訪問這個Web服務(wù):
地址/Webservice/Addservice.asmx/Add?a=10&b=5結(jié)果將以XML格式返回
在客戶機(jī)上部署這個服務(wù)
1.在命令行輸入:
WSDL地址/WebService/MathService.asmx /n:NameSp /out:FileName.cs這個操作將建立一個稱為FileName.cs的文件
說明:WSDL 指的是WebServices Description Language ,這個程序在Program Files\Microsoft.NET\FrameworkSDK\Bin 目錄中。
NameSp是我們設(shè)置的名字空間的名字,將在后面部署這個服務(wù)的客戶端的實(shí)現(xiàn)代碼中使用到。
2.編譯
CSC /t:library /r:system.web.dll /r:system.xml.dll FileName.cs
上述命令將生成一個dll文件,名字就是上面的asmx文件中的公共類的名字,在我們的例子中,就是:AddNumbers.dll
3.將生成的dll文件放到部署機(jī)的wwwroot\bin目錄中。
在部署機(jī)的asp/aspx 中調(diào)用這個Web Service
- <%@ import Namespace = "NameSp" %>
- <script language = "c#" runat = "server">
- public void Page_Load(object o, EventArgs e){
- int x = 10;
- int y = 5;
- int sum;
- //Instantiating the public class of the webservice
- AddNumbers AN = new AddNumbers();
- sum = AN.Add(x,y);
- string str = sum.ToString();
- response.writeline(str);
- }
- </script>
以上介紹C#建立Web Service
【編輯推薦】