下面,我們看看如何建立和部署一個最簡單的Web服務
建立Web服務
1.在wwwroot目錄下建立一個叫做Webservice的目錄。
2.建立下面這樣一個檔案:
<%@ WebService Language="c#" Class="AddNumbers"%>
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是副檔名),儲存到Webservice的目錄中
4.現在我們建立了Web服務,已經準備好用戶端使用
5.現在,你可以用下面的URL訪問這個Web服務:
http://IP地址/Webservice/Addservice.asmx/Add?a=10&b=5
結果將以XML格式返回。
在客戶機上部署這個服務
1.在命令列輸入:
WSDL http://IP地址/WebService/MathService.asmx /n:NameSp /out:FileName.cs
這個操作將建立一個稱為FileName.cs的檔案
說明:WSDL 指的是WebServices Description Language ,這個程式在Program Files\Microsoft.NET\FrameworkSDK\Bin 目錄中。
NameSp是我們設定的名字空間的名字,將在後面部署這個服務的用戶端的實現代碼中使用到。
2.編譯
CSC /t:library /r:system.web.dll /r:system.xml.dll FileName.cs
上述命令將產生一個dll檔案,名字就是上面的asmx檔案中的公用類的名字,在我們的例子中,就是:AddNumbers.dll
3.將產生的dll檔案放到部署機的wwwroot\bin目錄中。
在部署機的asp/aspx 中調用這個Web服務
<%@ 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>