在 Visual Studio 下構建 Web Service 服務非常簡單, 只需: 添加新的項目--> ASP.NET Web 服務應用程式,即可產生一個 WebService, 並有一個預設的 不帶參數的 Helloworld web方法, 也可自己添加一個帶參數的方法, 如下:
[WebMethod]
public string SayHello(string name)
{
return String.Format("Hi, {0}!", name);
}
產生的是一個 .DLL 檔案; 也可以將 Service.asmx 發布到 IIS中去.
(一) WinForm 中調用 WebService.
1. 添加一個新的項目: Windows表單應用程式;
2. 應用 --> 添加應用, 找到上面產生的 WebService 應用程式檔案(.dll), 添加當前應用程式的應用中.
3. 添加引用 WebSerice 的命名空間, 比如 : using MyWebService;
4. 測試調用web service 的效果: 在表單上設定 2個 Button, 設定Click事件:
private void button1_Click(object sender, EventArgs e) { MyWebService.Service1 localService = new Service1(); MessageBox.Show(localService.HelloWorld()); } private void button2_Click(object sender, EventArgs e) { MyWebService.Service1 localService = new Service1(); string response = localService.SayHello("Tom"); MessageBox.Show(response); }
即可.
(二) 瀏覽器下使用 Http-Get 直接調用 WebService, 即在瀏覽器下地址欄這樣調用:
http://DomainName/Service1.asmx/SayHello?name="Jick"
預設情況下, 處於安全考慮, .net 2.0 以上不支援這種協議調用. 若要這樣做, 則需要修改 web.config 設定檔, 如下增加設定項:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name ="HttpPost"/>
</protocols>
</webServices>
這個必須放在<system.web> ... </system.web> 區段裡的.
當 web服務發布時 web.config 是一起發布出去的.
開啟瀏覽器, 在地址欄輸入: http://127.0.0.1/Service1.asmx/SayHello?Name="dfasfas"
其中方法名 SayHello 大小寫是敏感的, 參數名不區分大小寫, 但名稱必須與原方法定義中是一樣的.
即可獲得如下 xml 資訊:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="
http://tempuri.org/">
Hi, "dfasfas"!</string> 當然這種顯示結果 UI 體驗是不友好的, 是給開發人員用於擷取 xml 資料的. 這就是對 Web Service 的一個初步瞭解吧.